-->

Enabling CORS with WebAPI PUT / POST requests?

2019-01-22 03:42发布

问题:

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:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <httpProtocol>
      <customHeaders>
        <!-- TODO: don't let anyone make requests - only approved clients -->
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="WebDAV" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule"/>
    </modules>
  </system.webServer>

But in chrome when I make a POST request I get the Not Allowed error:

My request looks like this:

var request = $.ajax({
            async: true,
            url: apiEndpoint + 'api/login',
            type: 'POST',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: 'json'
        })

apiEndpoint is on localhost but on a different port - the client and api projects are in different solutions.

The POST request eventually makes its way to the server, but I always get an error related to OPTIONS and I never get a cookie saved to the client because of it.

I spent the last couple hours trying to get CORS with WebAPI working:

https://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API

But some assembly versioning issues led to me yanking everything out - hopefully there's a simpler solution.

回答1:

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