Enable Cors in Web API 2

Enable CORS in Web API 2

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

CORS not enabled although configured for web API

CORS allows you to specify who is able to call your API. So more is needed than just enabling CORS; you need to set the policies. There are a couple ways to do that:

  1. With the [EnableCors] attribute, which can be set at either the Controller or Action level:
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]

  1. For your entire application:
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("[EnableCors(origins: "http://localhost:4200", "*", "*");
config.EnableCors(cors);
}

You can set the origin to "*" to allow any website to make requests to your API, but be careful with that.

More information here: Enable cross-origin requests in ASP.NET Web API 2

Cors not working in web api 2.0

Nothing worked for me.. after many tries I finally managed to get something working.

if you have the same problem..

1) remove anything related to cors from the nugget packages installed .. everything.

2) remove anything related to cors from the web.config.

3) In Gloabal.asax

protected void Application_BeginRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
var response = context.Response;

response.AddHeader("Access-Control-Allow-Origin", "*");
response.AddHeader("X-Frame-Options", "ALLOW-FROM *");

if (context.Request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PATCH, PUT");
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
response.AddHeader("Access-Control-Max-Age", "1000000");
response.End();
}
}

This work for both /api and /token.
This is a generic solution please be aware before deploying it to prod.

Hope will help anyone who has the same problem.

CORS and ASP.Net Web API

Please visit http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api. you will get a complete guide to implement CORS in WebAPI.

UPDATE:
To implement CORS in WEBAPI please follows these steps:

  1. Add the CORS NuGet package in your solution. In Visual Studio, from the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

    Install-Package Microsoft.AspNet.WebApi.Cors

  2. Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.

    public static class WebApiConfig
    {
    public static void Register(HttpConfiguration config)
    {
    // New code
    config.EnableCors();
    }
    }
  3. Next, add the [EnableCors] attribute to the BootStrapController class:

    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class BootStrapController : ApiController
    {
    // Controller methods
    }

    origins,headers and methods may vary according to your need.

How to enable cors in ASP.NET Core 6.0 Web API project?

The code that you posted seems to work fine. I pasted the code into a new .NET 6 project and the CORS headers are added in the response when a request like below is send from the browser.

fetch('http://localhost:7107/Weatherforecast').then(res => res.json()).then(e => console.log(e))

Results in the following response:

Sample Image

Enable CORS for Web Api 2 and OWIN token authentication

I know your issue was solved inside comments, but I believe is important to understand what was causing it and how to resolve this entire class of problems.

Looking at your code I can see you are setting the Access-Control-Allow-Origin header more than once for the Token endpoint:

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

And inside GrantResourceOwnerCredentials method:

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); 

This, looking at the CORS specifications, is itself an issue because:

If the response includes zero or more than one Access-Control-Allow-Origin header values, return fail and terminate this algorithm.

In your scenario, the framework is setting this header two times, and understanding how CORS must be implemented, this will result in the header removed in certain circumstances (possibly client-related).

This is also confirmed by the following question answer: Duplicate Access-Control-Allow-Origin: * causing COR error?

For this reason moving the call to app.UseCors after the call to ConfigureOAuth allows your CORS header to be set only once (because the owin pipeline is interrupted at the OAuth middleware, and never reaches the Microsoft CORS middleware for the Token endpoint) and makes your Ajax call working.

For a better and global solution you may try to put again app.UseCors before the OAuth middleware call, and remove the second Access-Control-Allow-Origin insertion inside GrantResourceOwnerCredentials.

Unable to enable CORS in WebAPI 2

you also need to add the appropriate http headers in your web.config:

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


Related Topics



Leave a reply



Submit