Enabling CORS with WebAPI PUT / POST requests?

后端 未结 1 660
日久生厌
日久生厌 2020-12-08 11:21

I\'ve tried following this post but I\'m still not quite there:

CORS support for PUT and DELETE with ASP.NET Web API

In my web.config I have the following: <

相关标签:
1条回答
  • 2020-12-08 12:03

    POST, PUT, DELETE, etc use pre-flighted CORS. The browser sends an OPTIONS request. Since you do not have an action method that handles OPTIONS, you are getting a 405. In its most simplest form, you must implement an action method like this in your controller.

    public HttpResponseMessage Options()
    {
        var response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.OK;
        return response;
    }
    

    One thing to note is that the customHeaders you have configured in web.config will already be adding the necessary Access-Control-Allow-Origin and Access-Control-Allow-Methods headers. So the action method is not doing the same.

    Implementing action method in controller works but may not be a good option. A better option will be to implement a message handler that does this for you. A much better option will be to use thinktecture identity model to enable CORS. Web API 2 has CORS support built-in (taken from ttidm).

    0 讨论(0)
提交回复
热议问题