Enable CORS for Web API 1, .net 4.0

前端 未结 3 936
梦毁少年i
梦毁少年i 2020-12-19 03:52

I need to enable CORS for my Web API and I can\'t upgrade to Framework 4.5 at the moment. (I know about System.Web.Http.Cors.EnableCorsAttribute.)

I\'ve tried to add

3条回答
  •  抹茶落季
    2020-12-19 04:16

    POST, PUT, DELETE, etc use pre-flighted CORS. The browser sends an OPTIONS request. This is because browser first, checks if serverside can handle CORS or not using OPTIONS request, if succeeds, then sends actual request PUT or POST or Delete. 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.

    More explanation - http://www.w3.org/TR/cors/#resource-preflight-requests

    http://www.html5rocks.com/en/tutorials/cors/

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

    Note: This this action just responds to OPTION request, so along with this you need to add necessary config to web.config, such as Access-Control-Allow-Origin = * and Access-Control-Allow-Methods = POST,PUT,DELETE.

    Web API 2 has CORS support, but with Web API 1, you have to follow this path.

提交回复
热议问题