Error:

Get the following error when trying to access api call from external sites.

Access to fetch at xxxx from origin xxxx has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Fix:

This needs to be fixed on the Web API, not the Blazor app.

Method 1: Via Custom Headers

This will automatically be applied to all services.

In the Web Api (backend) inside the Web.config between the <system.webServer> </ system.webServer> tags, insert the http protocol ex:

<system.webServer>

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

</system.webServer>

Method 2: Enable Cors for Specific Controller

This will only apply to specific class.

  1. Use NuGet to install Microsoft.AspNet.Cors
  2. Enable Cors in Register method of WebApiConfig.cs
config.EnableCors();
        public static void Register(HttpConfiguration config)
        {
            // Enable CORS.
            config.EnableCors();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

3. Set at specific controller

using System.Web.Http.Cors;

    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class ProductController : ApiController
    {
        
    }

Sources:

https://github.com/jaredhanson/passport/issues/582

https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

https://stackoverflow.com/questions/53298478/has-been-blocked-by-cors-policy-response-to-preflight-request-doesn-t-pass-acce

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Last modified: December 11, 2020

Author

Comments

Write a Reply or Comment