MVC web api: header "Access-Control-Allow-Origin" is missing 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 am trying to get data from webAPI2 (MVC5) for use in another domain using angularJS.

my controller is as follows:

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; } } } 
+107
angularjs c # asp.net-mvc cors asp.net-web-api
Dec 16 '14 at 12:03
source share
12 answers

You need to enable CORS in Web Api . A simpler and preferred way to enable CORS around the world is to add the following to 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 all methods are set individually, instead of using * . This is due to the fact that when using * an error appears.

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(); // ... } } 

You can then use the [EnableCors] attribute in actions or controllers such as

 [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")] 

Or you can register it worldwide

 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 Options preview requests with HTTP OPTIONS requests.

Web API should respond to the Options request to confirm that it is indeed configured to support CORS .

To handle this, all you have to do is send a blank answer. You can do this inside your actions, or you can do it globally as follows:

 # Global.asax.cs protected void Application_BeginRequest() { if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") { Response.Flush(); } } 

This additional check has been added to ensure that older APIs that were designed to accept only GET and POST requests will not be used. Imagine that you sent a DELETE request to the API when this verb did not exist. The result is unpredictable, and the results can be dangerous.

+271
Dec 16 '14 at 12:13
source share

@ The answer of Mihai-Andrei Dinkulescu is correct, but in the interests of search engines there is also a thin point that can cause this error.

Adding '/' to the end of your URL will stop EnableCors in all instances (e.g. from the home page).

those. 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 the EnableCors attribute is used.

+24
Jun 17 '15 at 8:11
source share

I followed all the steps indicated by Mihai-Andrei Dinkulescu .
But in my case, I needed step 1 more , because http OPTIONS was disabled in Web.Config on the line below.

<remove name="OPTIONSVerbHandler" />

I just deleted it from Web.Config (just comment it as shown below) and Cors works like a charm

 <handlers> <!-- remove name="OPTIONSVerbHandler" / --> </handlers> 
+19
Jan 14 '16 at 13:02
source share

Perhaps this is due to the installation of Cors nuget packages.

If you encounter a problem after installing and installing the code from nuget, you can try reinstalling Web Api.

In the package manager, run Update-Package Microsoft.AspNet.WebApi -reinstall

+9
Jul 30 '16 at 21:45
source share

Try this to make sure you set CORS correctly:

 [EnableCors(origins: "*", headers: "*", methods: "*")] 

Still not working? Check for HTTP headers.

+6
Dec 16 '14 at 12:09
source share

For the CORS protocol to work, you need to have an OPTIONS method on each endpoint (or a global filter using this method) that will return these headers:

 Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Headers: content-type 

The reason is that the browser will first send an OPTIONS request to "check" your server and view permissions

+4
Dec 16 '14 at 12:12
source share

@ Answer by Mihai-Andrei Dinkulescu worked for me, for example:

  • Adding <httpProtocol> to the web.config <system.webServer> section
  • Returning an empty response for OPTIONS requests through the mentioned Application_BeginRequest() in global.asax

Except that checking it for Request.Headers.AllKeys.Contains("Origin") did NOT work for me because the request contained origing , therefore lowercase. I think my browser (Chrome) sends it this way for CORS requests.

I solved this more universally, using the case - insensitive version of my Contains check instead: if (culture.CompareInfo.IndexOf(string.Join(",", Request.Headers.AllKeys), "Origin", CompareOptions.IgnoreCase) >= 0) {

+1
Apr 29 '16 at 19:53 on
source share
 Please make this change in webapi.config file to enable cors and avoid the below error 

asp.net webapi The response to the preliminary check request does not pass the access control check: the requested resource does not have the "Access-Control-Allow-Origin" header.

 public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); //... existing values in register seection } 

}

0
Jul 13 '18 at 11:04
source share

I caught the following case about corso. Maybe this is useful to someone. If you add the WebDav Redirector function to your server, PUT and DELETE requests are not executed.

So you need to remove the "WebDAVModule" from your IIS server:

  • "In the configuration of the IIS modules, commit the WebDAVModule if it is on your web server, and then remove it."

Or add to your config:

 <system.webServer> <modules> <remove name="WebDAVModule"/> </modules> <handlers> <remove name="WebDAV" /> ... </handlers> 

0
Nov 05 '18 at 7:57
source share

If your web.config file contains security \ requestFiltering nodes, follow these steps:

 <security> <requestFiltering> <verbs allowUnlisted="false"> <add verb="GET" allowed="true" /> <add verb="POST" allowed="true" /> <add verb="PUT" allowed="true" /> <add verb="DELETE" allowed="true" /> <add verb="DEBUG" allowed="true" /> </verbs> </requestFiltering> 

make sure you add this as well

 <add verb="OPTIONS" allowed="true" /> 
0
Dec 19 '18 at 9:36
source share

I tried everything I could find on the net, including the methods that were given in this answer. After an almost complete attempt to solve the problem within a whole day, I found a solution that worked for me like a charm.

in the WebApiConfig file in the App_Start folder , comment out all lines of code and add the following code:

 'public static void Register(HttpConfiguration config) { // Web API configuration and services config.EnableCors(); var enableCorsAttribute = new EnableCorsAttribute("*", "Origin, Content-Type, Accept", "GET, PUT, POST, DELETE, OPTIONS"); config.EnableCors(enableCorsAttribute); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", //routeTemplate: "api/{controller}/{id}", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.Add(new BrowserJsonFormatter()); } public class BrowserJsonFormatter : JsonMediaTypeFormatter { public BrowserJsonFormatter() { this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); this.SerializerSettings.Formatting = Formatting.Indented; } public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { base.SetDefaultContentHeaders(type, headers, mediaType); headers.ContentType = new MediaTypeHeaderValue("application/json"); } }' 
0
Apr 13 '19 at 21:14
source share

I know that I will come to this very late. However, for everyone who was looking, I thought I would post what FINALLY works for me. I do not pretend to be the best solution - only that it worked.

Our WebApi service uses the config.EnableCors (corsAttribute) method. However, even with this, it would still refuse pre-flight requests. @ Mihai-Andrei Dinkulescu's answer gave me a hint. First of all, I added its Application_BeginRequest () code to clear option requests. This still does not work for me. The problem is that the WebAPI still does not add the expected headers to the OPTIONS request. Flushing alone did not work - but it gave me an idea. I added custom headers that would otherwise be added via web.config in response to an OPTIONS request. Here is my code:

 protected void Application_BeginRequest() { if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") { Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:44343"); Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); Response.Headers.Add("Access-Control-Allow-Credentials", "true"); Response.Flush(); } } 

Obviously this only applies to OPTIONS requests. All other verbs are processed by the CORS configuration. If there is a better approach to this, I am all ears. It seems like a cheat to me, and I would prefer that the headers be added automatically, but this is what eventually worked and allowed me to move on.

0
Jul 08 '19 at 18:24
source share



All Articles