Enable CORS in Web API 2

C#asp.net Web-ApiCors

C# Problem Overview


I have client and a server running on different ports. The server is running Web API 2 (v5.0.0-rc1).

I tried installing the Microsoft ASP.NET Web API Cross-Origin Support package and enabled it in WebApiConfig.cs. It gives me the EnableCors() function, so the package was installed correctly.

Here you can see my Register() function in WebApiConfig.cs:

public static void Register(HttpConfiguration config)
{
	config.MapHttpAttributeRoutes();

	var cors = new EnableCorsAttribute("*", "*", "*");
	config.EnableCors(cors);
}

GET requests work fine. But when sending POST, I get the following:

OPTIONS http://localhost:19357/api/v1/rooms? 404 (Not Found) angular.js:10159
OPTIONS http://localhost:19357/api/v1/rooms? Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. angular.js:10159
XMLHttpRequest cannot load http://localhost:19357/api/v1/rooms. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.

According to Fiddler it only sends the OPTIONS request. It doesn't issue the POST afterwards.

So I'm guessing the config.EnableCors(cors); in the WebApiConfig.cs isn't doing anything, which leads to the server denying the client/browser to send a POST request.

Do you have any idea how to solve this problem?

EDIT 05.09.13 This has been fixed in 5.0.0-rtm-130905

C# Solutions


Solution 1 - C#

CORS works absolutely fine in Microsoft.AspNet.WebApi.Cors version 5.2.2. The following steps configured CORS like a charm for me:

  1. Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2" // run from Package manager console

  2. In Global.asax, add the following line: BEFORE ANY MVC ROUTE REGISTRATIONS

    GlobalConfiguration.Configure(WebApiConfig.Register);
    
  3. In the WebApiConfig Register method, have the following code:

    public static void Register(HttpConfiguration config)
    {
    	config.EnableCors();
    	config.MapHttpAttributeRoutes();
    }
    

In the web.config, the following handler must be the first one in the pipeline:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

In the controller derived from ApiController, add the EnableCorsAttribute:

[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController

That should set you up nicely!

Solution 2 - C#

I didn't need to install any package. Just a simple change in your WebAPI project's web.config is working great:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

Credit goes to: Using CORS in ASP.NET WebAPI Without Being a Rocket Scientist

Solution 3 - C#

For reference using the [EnableCors()] approach will not work if you intercept the Message Pipeline using a DelegatingHandler. In my case was checking for an Authorization header in the request and handling it accordingly before the routing was even invoked, which meant my request was getting processed earlier in the pipeline so the [EnableCors()] had no effect.

In the end found an example CrossDomainHandler class (credit to shaunxu for the Gist) which handles the CORS for me in the pipeline and to use it is as simple as adding another message handler to the pipeline.

public class CrossDomainHandler : DelegatingHandler
    {
        const string Origin = "Origin";
        const string AccessControlRequestMethod = "Access-Control-Request-Method";
        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool isCorsRequest = request.Headers.Contains(Origin);
            bool isPreflightRequest = request.Method == HttpMethod.Options;
            if (isCorsRequest)
            {
                if (isPreflightRequest)
                {
                    return Task.Factory.StartNew(() =>
                    {
                        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                        string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                        if (accessControlRequestMethod != null)
                        {
                            response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                        }

                        string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
                        if (!string.IsNullOrEmpty(requestedHeaders))
                        {
                            response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                        }

                        return response;
                    }, cancellationToken);
                }
                else
                {
                    return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                    {
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                        return resp;
                    });
                }
            }
            else
            {
                return base.SendAsync(request, cancellationToken);
            }
        }
    }

To use it add it to the list of registered message handlers

config.MessageHandlers.Add(new CrossDomainHandler());

Any preflight requests by the Browser are handled and passed on, meaning I didn't need to implement an [HttpOptions] IHttpActionResult method on the Controller.

Solution 4 - C#

I'm most definitely hitting this issue with attribute routing. The issue was fixed as of 5.0.0-rtm-130905. But still, you can try out the nightly builds which will most certainly have the fix.

To add nightlies to your NuGet package source, go to Tools -> Library Package Manager -> Package Manager Settings and add the following URL under Package Sources: http://myget.org/F/aspnetwebstacknightly

Solution 5 - C#

Make sure that you are accessing the WebAPI through HTTPS.

I also enabled cors in the WebApi.config.

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

But my CORS request did not work until I used HTTPS urls.

Solution 6 - C#

 var cors = new EnableCorsAttribute("*","*","*");
 config.EnableCors(cors);

 var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);

Solution 7 - C#

Late reply for future reference. What was working for me was enabling it by nuget and then adding custom headers into web.config.

Solution 8 - C#

To enable CORS, 1.Go to App_Start folder. 2.add the namespace 'using System.Web.Http.Cors'; 3.Open the WebApiConfig.cs file and type the following in a static method.

config.EnableCors(new EnableCorsAttribute("https://localhost:44328",headers:"*", methods:"*"));

Solution 9 - C#

Below code worked for me,

App_Start -> WebApiConfig

EnableCorsAttribute cors = new EnableCorsAttribute("\*", "\*", "GET,HEAD,POST");
config.EnableCors(cors);

Solution 10 - C#

This solved my issue:

in Web.config>>Inside system.webServer tags:

 <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="GET,POST,PUT, DELETE, OPTIONS" />
            <add name="Access-Control-Allow-Headers" value="*" />
			<add name="Access-Control-Allow-Credentials" value="true" />
        </customHeaders>
    </httpProtocol>

And uncomment or delete this line inside system.webServer:

<remove name="OPTIONSVerbHandler"/>

Also, you need to declare enable cors either in webapiconfig.cs or in web.config. If you declare in both you may get an error something like :

'....origin 'www.example.com' blocked by cors policy due to multiple No 'Access-Control-Allow-Origin'('*','*').'

This did the trick for me.

Solution 11 - C#

As far as I understood, the server got to have a header that specifies that Access from Origin is Allowed i.e. a request from the same server could be responded to.

I used the following code :

// create a response object of your choice
var response = Request.CreateResponse(HttpStatusCode.OK);

//add the header
//replace the star with a specific name if you want to restrict access
response.Headers.Add("Access-Control-Allow-Origin", "*");

//now you could send the response and it should work...
return response;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGauiView Question on Stackoverflow
Solution 1 - C#Sudhanshu MishraView Answer on Stackoverflow
Solution 2 - C#Mosharaf HossainView Answer on Stackoverflow
Solution 3 - C#user692942View Answer on Stackoverflow
Solution 4 - C#GauiView Answer on Stackoverflow
Solution 5 - C#tno2007View Answer on Stackoverflow
Solution 6 - C#VikasView Answer on Stackoverflow
Solution 7 - C#MariuszView Answer on Stackoverflow
Solution 8 - C#user12319595View Answer on Stackoverflow
Solution 9 - C#Pallavi KulalView Answer on Stackoverflow
Solution 10 - C#krishView Answer on Stackoverflow
Solution 11 - C#JitinView Answer on Stackoverflow