Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3
I've created a pared-down demo project for you.
- Source: https://github.com/bigfont/webapi-cors
- Api Link: https://cors-webapi.azurewebsites.net/api/values
You can try the above API Link from your local Fiddler to see the headers. Here is an explanation.
Global.ascx
All this does is call the WebApiConfig
. It's nothing but code organization.
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
WebApiConfig.cs
The key method for your here is the EnableCrossSiteRequests
method. This is all that you need to do. The EnableCorsAttribute
is a globally scoped CORS attribute.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
EnableCrossSiteRequests(config);
AddRoutes(config);
}
private static void AddRoutes(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/"
);
}
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
}
}
Values Controller
The Get
method receives the EnableCors
attribute that we applied globally. The Another
method overrides the global EnableCors
.
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] {
"This is a CORS response.",
"It works from any origin."
};
}
// GET api/values/another
[HttpGet]
[EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
public IEnumerable<string> Another()
{
return new string[] {
"This is a CORS response. ",
"It works only from two origins: ",
"1. www.bigfont.ca ",
"2. the same origin."
};
}
}
Web.config
You do not need to add anything special into web.config. In fact, this is what the demo's web.config looks like - it's empty.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>
Demo
var url = "https://cors-webapi.azurewebsites.net/api/values"
$.get(url, function(data) { console.log("We expect this to succeed."); console.log(data);});
var url = "https://cors-webapi.azurewebsites.net/api/values/another"
$.get(url, function(data) { console.log(data);}).fail(function(xhr, status, text) { console.log("We expect this to fail."); console.log(status);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enable CORS on my Web API not working
You forgot to tell the AppBuilder to use cors.
Try and add the following line in the Startup Configuration method
app.UseCors(CorsOptions.AllowAll);
Intermittent CORS Issue with WebAPI 2 after I added a DelegatingHandler
I've worked out what the problem was, the intermittent bug was due to the logic which I placed inside the CustomInterceptor : DelegatingHandler
.
Adding the DelegatingHandler causes a pre-flight request, hence the SendAsync
method executes twice in very quick succession (which I was not expecting, hence the bug). On the first call (pre-flight), my logic allowed the base method to be called
var response = await base.SendAsync(request, cancellationToken);
, but on the second call (actual GET), my logic was returning to the client ("hey too many calls within a short period"), without proceeding to the above base method or inner handlers!
So the Browser reported this bypass as ...has been blocked by CORS policy: No 'Access-Control-Allow-Origin'...etc
.
EnableCors not working in WebApi
Seems like you are using MVC Controller instead of Api Controller (unless its DotNet Core). Change the Base class to ApiController
with action return type IHttpResponseMessage
and return Ok (new { test = "test message" });
Related Topics
How to Embed an Application Manifest into an Application Using VS2008
For Loop Not Returning Expected Value - C# - Blazor
Why Are Subjects Not Recommended in .Net Reactive Extensions
Passing an Enum Value as Command Parameter from Xaml
Convert File Path to a File Uri
Use of SQLparameter in SQL Like Clause Not Working
Md5 Hash with Salt for Keeping Password in Db in C#
Is There Windows System Event on Active Window Changed
How to Get Around the "'" Problem in SQLite and C#
When to Use Ilist and When to Use List
Getting All Controllers and Actions Names in C#
Displayname Attribute VS Display Attribute
How to Add a Custom Routed Command in Wpf