简体   繁体   English

Web API 2 Cors请求错误

[英]Web API 2 Cors Request Error

I am trying to get CORS set up for a project I am working on with WebAPI 2. I started having issues, so I created a demo app directly from asp.net forums here . 我试图为正在使用WebAPI 2的项目设置CORS。我开始遇到问题,因此我直接从此处的 asp.net论坛创建了一个演示应用程序。 Everything was working correctly until I needed to use json as the content type. 一切正常,直到我需要使用json作为内容类型。 Then I started getting: 然后我开始得到:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

I understand with this content type sends preflight requests, but I am dumbfounded how I can get this to pass. 我知道此内容类型会发送预检请求,但我对如何使它通过感到困惑。 Am I missing something? 我想念什么吗? As soon as I remove the "contentType: 'application/json'" attribute from AJAX request, it works. 一旦我从AJAX请求中删除了“ contentType:'application / json'”属性,它就会起作用。

TestController.cs 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 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 Request Ajax请求

$.ajax({
            type: "POST",
            url: 'http://localhost:17515/',
            data: JSON.stringify("Test"),
            xhrFields: {
                withCredentials: true
            },
            contentType: "application/json"
        });

在此输入图像描述

在此输入图像描述

It client will first send an OPTIONS request to the server. 它的客户端将首先向服务器发送OPTIONS请求。 To this request, the server should add a header: 对于此请求,服务器应添加标头:

Access-Control-Allow-Origin: http://localhost:17822

This indicates that the API running on port 17515 accepts requests from the client served by port 17822. 这表明在端口17515上运行的API接受来自端口17822服务的客户端的请求。

You could try changing your attribute to: 您可以尝试将属性更改为:

[EnableCors(origins: "http://localhost:17822", headers: "*", methods: "*")]

We haven't had good experiences using EnableCors , so we handle OPTIONS requests using OWIN, simply returning 200 OK and manually adding the appropriate headers to all OPTIONS request sent by approved origins. 我们没有使用EnableCors良好经验,因此我们使用OWIN处理OPTIONS请求,只需返回200 OK,然后将适当的标头手动添加到批准的来源发送的所有OPTIONS请求中即可。

There is a good article on CORS on MSDN (likely you have already seen it): https://msdn.microsoft.com/en-us/magazine/dn532203.aspx 在MSDN上有一篇有关CORS的好文章(可能您已经看过): https : //msdn.microsoft.com/zh-cn/magazine/dn532203.aspx

In your WebApiConfig.cs, you could try enabling the cors attributes there instead of on the controller. 在WebApiConfig.cs中,您可以尝试在此处而不是在控制器上启用cors属性。

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

rather than just 而不只是

        config.EnableCors();

This is working on a test project I have running at the moment. 这正在处理我目前正在运行的测试项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM