Enabling CORS with WebAPI PUT / POST requests?

断了今生、忘了曾经 提交于 2019-11-28 05:59:14
Badri

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!