Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, July 30, 2016

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

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 GetMainItems()          {                  HomePageDALcs dal = new HomePageDALcs();              //Three product added to display the data                //HomePagePromotedItems.Value.Add(new HomePagePromotedItem.Value.FirstOrDefault((p) => p.ID == id));                  List items = dal.MobileSelectTopSecondaryItemsByCategory(3, 5);              return items;            }            }  }  

Answer by Andrei M for MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource


Try this, to make sure you configured CORS correctly:

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

Still not working? Check HTTP headers presence.

Answer by sam for MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource


To make any CORS protocol to work, you need to have a OPTIONS method on every endpoint (or a global filter with this method) that will return those 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 send first an OPTIONS request to 'test' your server and see the authorizations

Answer by Mihai-Andrei Dinculescu for MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource


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

                                                

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.

Answer by HockeyJ for MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource


@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.

Answer by AlbertSY for MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource


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.

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

        

Answer by Bart for MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource


@Mihai-Andrei Dinculescu's answer worked for me, e.g.:

  • Adding a in the web.config's section
  • Returning empty response for OPTIONS requests via the mentioned Application_BeginRequest() in global.asax

Except that his check for Request.Headers.AllKeys.Contains("Origin") did NOT work for me, because the request contained an origing, so with lowercase. I think my browser (Chrome) sends it like this for CORS requests.

I solved this a bit more generically by using a case insensitive variant of his Contains check instead: if (culture.CompareInfo.IndexOf(string.Join(",", Request.Headers.AllKeys), "Origin", CompareOptions.IgnoreCase) >= 0) {

Answer by Bimal Das for MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource


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


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.