MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource
I tried everything that is written in this article: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api, but nothing works. I'm trying to get data from webAPI2 (MVC5) to use in another domain using angularJS.
my controller looks like this:
namespace tapuzWebAPI.Controllers
{
[EnableCors(origins: "http://local.tapuz.co.il", headers: "*", methods: "*", SupportsCredentials = true)]
[RoutePrefix("api/homepage")]
public class HomePageController : ApiController
{
[HttpGet]
[Route("GetMainItems")]
//[ResponseType(typeof(Product))]
public List<usp_MobileSelectTopSecondaryItemsByCategoryResult> GetMainItems()
{
HomePageDALcs dal = new HomePageDALcs();
//Three product added to display the data
//HomePagePromotedItems.Value.Add(new HomePagePromotedItem.Value.FirstOrDefault((p) => p.ID == id));
List<usp_MobileSelectTopSecondaryItemsByCategoryResult> items = dal.MobileSelectTopSecondaryItemsByCategory(3, 5);
return items;
}
}
}
You need to enable CORS in your Web Api. The easier and preferred way to enable CORS globally is to add the following into web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Please note that the Methods are all individually specified, instead of using *
. This is because there is a bug occurring when using *
.
You can also enable CORS by code.
Update
The following NuGet package is required: Microsoft.AspNet.WebApi.Cors
.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
// ...
}
}
Then you can use the [EnableCors]
attribute on Actions or Controllers like this
[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
Or you can register it globally
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("http://www.example.com", "*", "*");
config.EnableCors(cors);
// ...
}
}
You also need to handle the preflight Options
requests with HTTP OPTIONS
requests.
Web API
needs to respond to the Options
request in order to confirm that it is indeed configured to support CORS
.
To handle this, all you need to do is send an empty response back. You can do this inside your actions, or you can do it globally like this:
# Global.asax.cs
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
This extra check was added to ensure that old APIs
that were designed to accept only GET
and POST
requests will not be exploited. Imagine sending a DELETE
request to an API
designed when this verb didn't exist. The outcome is unpredictable and the results might be dangerous.
@Mihai-Andrei Dinculescu's answer is correct, but for the benefit of searchers, there is also a subtle point that can cause this error.
Adding a '/' on the end of your URL will stop EnableCors from working in all instances (e.g. from the homepage).
I.e. This will not work
var cors = new EnableCorsAttribute("http://testing.azurewebsites.net/", "*", "*");
config.EnableCors(cors);
but this will work:
var cors = new EnableCorsAttribute("http://testing.azurewebsites.net", "*", "*");
config.EnableCors(cors);
The effect is the same if using the EnableCors Attribute.
I followed all the steps above indicated by Mihai-Andrei Dinculescu.
But in my case, I needed 1 more step because http OPTIONS was disabled in the Web.Config by the line below.
<remove name="OPTIONSVerbHandler" />
I just removed it from Web.Config (just comment it like below) and Cors works like a charm
<handlers>
<!-- remove name="OPTIONSVerbHandler" / -->
</handlers>
It may be because of the installation of Cors nuget packages.
If you facing the problem after installing and enabaling cors from nuget , then you may try reinstalling web Api.
From the package manager, run Update-Package Microsoft.AspNet.WebApi -reinstall
Try this, to make sure you configured CORS correctly:
[EnableCors(origins: "*", headers: "*", methods: "*")]
Still not working? Check HTTP headers presence.