4
votes

Can you please help me on how do I enable CORS in FireFox and Chrome. The WebAPi is working fine with Internet but not with Chrome/Firefox.

This is what I am getting in firefox console.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:51/api/abcservice/M2. This can be fixed by moving the resource to the same domain or enabling CORS.

Thanks in advance.

3

3 Answers

3
votes

CORS is not browser dependent, you must enable it server-side.

Install CORS WebApi NuGet package :

Install-Package Microsoft.AspNet.WebApi.Cors

Then at application start :

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // CORS
        config.EnableCors();

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

Source

0
votes

With Web API, sometime you get the CORS error when your request encounter an exception on the server side, so make sure that you debug the request on the Web API controller, and double check that the origin header is set to the response.

0
votes

Unlikely IE and Edge, Chrome and Firefox make an additional OPTIONS request before each GET or POST, that's why you should configure the attribute for it explicitly in the global.asax. Try this code:

protected void Application_BeginRequest(object sender, EventArgs e)
{
        HttpContext.Current.Response.AddHeader("access-control-allow-origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "options") 
        {
            HttpContext.Current.Response.AddHeader("access-control-allow-methods", "post, put, delete, get");
            HttpContext.Current.Response.AddHeader("access-control-allow-headers", "content-type, accept");
            HttpContext.Current.Response.AddHeader("access-control-max-age", "1728000");
            HttpContext.Current.Response.End();
        }
}