从 Angular 到不同域上的 webAPI 的调用变成了 OPTIONS

Call from Angular to webAPI on different domain is turned into OPTIONS

我正在使用 asp.net WebAPI 和 Angular。当我从 Angular 调用我的 WebAPI 上的方法时,我在 Chrome 中收到一个错误(它在 IE 中工作正常),我可以通过 Fiddler 看到调用是作为一个"OPTIONS"(我只用了$http.post和$http.get),在IE中它被制作成post或get。

我尝试配置一个 header 来发送请求 ('Content-Type': 'text/plain'),然后它在 Chrome 中工作正常。但问题是我正在使用也在 header 中的授权,当我在 header 中添加授权时,content-type 的 hack 不再起作用。

我还尝试将 NuGet 包 "Cors" 添加到 WebAPI(并在控制器中启用它 [EnableCors("", "", "* ")]), 但它并没有做任何改变。

有人解决这个问题吗?

提前致谢:-)

你们在使用cors的时候,是否也在Global.asax的Application_Start方法中添加了代码?不只是添加 EnableCorsAttributeon action

GlobalConfiguration.Configuration.EnableCors();

或者你不需要使用cors lib,在web.config的节点system.webServer

中添加子节点时也使用它
<httpProtocol>    
  <customHeaders>    
    <add name="Access-Control-Allow-Origin" value="*" />    
    <add name="Access-Control-Allow-Headers" value="*" />    
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />    
  </customHeaders>    
</httpProtocol>

您可能想要添加一个 httpInterceptor 并添加 Access-Control headers,如类似问题 this answer 中所述