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.
- Use NuGet to install Microsoft.AspNet.Cors
- 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
{
}
Comments