Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cors not working in web api 2.0

I'm trying very hard to understand and enable CORS in a web api project. I've hit a blocking point. I've started with an ASP.NET MVC Web Api 2 project with an ASP.NET identity. Whatever I do seems to not work.

I've deleted my global.asx file and my startup looks like this:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
          HttpConfiguration configuration = new HttpConfiguration();
          // I'm not sure it this is the proper way to use webapiconfig
          WebApiConfig.Register(configuration);
          app.UseWebApi(configuration);
          app.UseCors(CorsOptions.AllowAll);
          ConfigureAuth(app);
    }
}

and the WebApiConfig.Register code is:

public static void Register(HttpConfiguration config)
{
     // Web API configuration and services
     // Configure Web API to use only bearer token authentication.
     config.SuppressDefaultHostAuthentication();
     config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
     config.AddODataQueryFilter();

     // Web API routes
     config.MapHttpAttributeRoutes();

     config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
     );

     var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
     jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
     RegisterModels(); //Automapper here
}

I have the mc aspnet cors and microsoft owin host System web installed. The "[assembly: OwinStartup(typeof(MyProject.Startup))]" is in place, and in the web.config I have:

<appSettings>
  <add key="owin:AutomaticAppStartup" value="true" />          
</appSettings>

I only call app.UseCors(CorsOptions.AllowAll) to enable CORS, no other way like config.enableCors or anything else, but whenever I try getting the token or anything in the API, I get the error:

Reason: CORS header ‘Access-Control-Allow-Origin’ missing.

I have tried putting a breakpoint in the Configuration method but it is not called... ever. I'm debugging with IIS Express.

like image 508
ionut spataru Avatar asked Feb 05 '23 21:02

ionut spataru


1 Answers

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.

like image 143
ionut spataru Avatar answered Mar 17 '23 02:03

ionut spataru