Tuesday, May 29, 2018

Web API CORS configuration : The requested resource does not support http method 'OPTIONS' error

After creating a web api project from VS 2015 template I was not able to authenticate (or access any other controller method) using ajax query.


After searching for some time I found out that config.EnableCors(); method call in WebApiConfig file can solve this problem.

However, this extension method is not available until Microsoft.AspNet.WebApi.Cors nuget package has been added to the project. The code is as show below:

<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>
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("http://www.example.com", "*", "*");
        config.EnableCors(cors);

        // ...
    }
}
# Global.asax.cs
protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}
To call the api method from jquery client application use this format:
        var url = "https://localhost:44331/api/values";
     
 
        $.ajax({
            type: "GET",
            //headers: { "X-My-Custom-Header": "some value" },
            url: url
        }).done(function (data) {
            console.log(data);
        });
Copied from: https://stackoverflow.com/questions/27504256/mvc-web-api-no-access-control-allow-origin-header-is-present-on-the-requested




No comments:

SSL Error - The connection for this site is not secure

 After cloning a git repo of dot net framework website and trying to run it all I could see was this error Turns out the fix was to simply e...