Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling CORS with WebAPI PUT / POST requests?

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:

enter image description here

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.

like image 717
SB2055 Avatar asked Jul 06 '13 01:07

SB2055


People also ask

How do I fix the CORS issue in Web API?

Say the front-end is served from https://demodomain-ui.com and the backend is served from from https://demodomain-service.com/api. If an end user tries to access the application, for security reasons the browsers restrict cross-origin HTTP requests initiated from the UI. The first is to install the Microsoft. AspNet.

Should API enable CORS?

CORS is typically required to build web applications that access APIs hosted on a different domain or origin. You can enable CORS to allow requests to your API from a web application hosted on a different domain.


1 Answers

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

like image 107
Badri Avatar answered Sep 28 '22 04:09

Badri