我有客户端和服务器在不同的端口上运行。服务器正在运行 Web API 2 (v5.0.0-rc1)。
我尝试安装 Microsoft ASP.NET Web API Cross-Origin Support package并在 WebApiConfig.cs
中启用它。它为我提供了 EnableCors()
函数,因此该包已正确安装。
在这里,您可以在 WebApiConfig.cs
中看到我的 Register()
函数:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
GET
请求工作正常。但是当发送 POST
时,我得到以下信息:
OPTIONS http://localhost:19357/api/v1/rooms? 404 (Not Found) angular.js:10159
OPTIONS http://localhost:19357/api/v1/rooms? Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. angular.js:10159
XMLHttpRequest cannot load http://localhost:19357/api/v1/rooms. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.
根据 Fiddler,它只发送 OPTIONS
请求。之后它不会发出 POST
。
所以我猜测 WebApiConfig.cs
中的 config.EnableCors(cors);
没有做任何事情,这导致服务器拒绝客户端/浏览器发送 POST
请求。
你知道如何解决这个问题吗?
编辑 05.09.13 这已在 5.0.0-rtm-130905 中修复
最佳答案
CORS 在 Microsoft.AspNet.WebApi.Cors
版本 5.2.2 中工作得非常好。以下步骤对我来说配置 CORS 就像一个魅力:
Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2"
//从包管理器控制台运行在 Global.asax 中,添加以下行:在任何 MVC 路由注册之前
GlobalConfiguration.Configure(WebApiConfig.Register);
在
WebApiConfig
注册方法中,有如下代码:public static void Register(HttpConfiguration config) { config.EnableCors(); config.MapHttpAttributeRoutes(); }
在 web.config 中,以下处理程序必须是管道中的第一个处理程序:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
在派生自 ApiController
的 Controller 中,添加 EnableCorsAttribute
:
[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController
这应该让你很好地设置!
关于c# - 在 Web API 2 中启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18619656/