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:

c# httpclient The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

 If we get this error while trying to get http reponse using HttpClient object, it could mean that certificate validation fails for the remo...