Gentenator
Gentenator

Reputation: 207

WebApi 2.2 Cross-Origin Support

I'm trying to add CORS support to my API. I've added the nuget package Microsoft.AspNet.WebApi.Cors. I've added this to my WebgApiConfig.cs file, in Register

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

I've also tried configuring at the Controller. No matter what I try, the Access-Control-Allow-Origin header doesn't get added to the response and I get this message in Chrome when I execute javascript

No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:19560' is therefore not allowed access. The response had HTTP status code 401

Any thoughts on what I may be missing?

It now works if I set the ajax contentType contentType: 'text/plain'

Apparently this is needed because no route handles the preflight Options request from the browser. Now I need to figure out how to handle the preflight options check so I don't have to set the contentType.

Upvotes: 2

Views: 1066

Answers (1)

firepol
firepol

Reputation: 1751

A very good tutorial with solution for cross-origin support via CORS:

http://www.codeproject.com/Articles/843044/Getting-started-with-AngularJS-and-ASP-NET-MVC-The

It's actually just a nuget package to install:

Install-Package Microsoft.Owin.Cors

In Startup.cs, amend Configuration so it contains the following:

public void Configuration(IAppBuilder app)
{
  app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
  ConfigureAuth(app);
}

Upvotes: 1

Related Questions