[英]Web API 2 Cors Request Error
我试图为正在使用WebAPI 2的项目设置CORS。我开始遇到问题,因此我直接从此处的 asp.net论坛创建了一个演示应用程序。 一切正常,直到我需要使用json作为内容类型。 然后我开始得到:
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
我知道此内容类型会发送预检请求,但我对如何使它通过感到困惑。 我想念什么吗? 一旦我从AJAX请求中删除了“ contentType:'application / json'”属性,它就会起作用。
TestController.cs
[Authorize]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class TestController : ApiController
{
// GET api/<controller>
public HttpResponseMessage Get()
{
return new HttpResponseMessage()
{
Content = new StringContent("GET: Test message")
};
}
public HttpResponseMessage Post([FromBody]string name)
{
return new HttpResponseMessage()
{
Content = new StringContent("POST: Test message")
};
}
public HttpResponseMessage Put()
{
return new HttpResponseMessage()
{
Content = new StringContent("PUT: Test message")
};
}
}
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Ajax请求
$.ajax({
type: "POST",
url: 'http://localhost:17515/',
data: JSON.stringify("Test"),
xhrFields: {
withCredentials: true
},
contentType: "application/json"
});
它的客户端将首先向服务器发送OPTIONS
请求。 对于此请求,服务器应添加标头:
Access-Control-Allow-Origin: http://localhost:17822
这表明在端口17515上运行的API接受来自端口17822服务的客户端的请求。
您可以尝试将属性更改为:
[EnableCors(origins: "http://localhost:17822", headers: "*", methods: "*")]
我们没有使用EnableCors
良好经验,因此我们使用OWIN处理OPTIONS请求,只需返回200 OK,然后将适当的标头手动添加到批准的来源发送的所有OPTIONS请求中即可。
在MSDN上有一篇有关CORS的好文章(可能您已经看过): https : //msdn.microsoft.com/zh-cn/magazine/dn532203.aspx
在WebApiConfig.cs中,您可以尝试在此处而不是在控制器上启用cors属性。
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
而不只是
config.EnableCors();
这正在处理我目前正在运行的测试项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.