Supporting HTTP Method OPTIONS

If your client code is calling the Web API in javaScript, the execution will be fine on Http GET and POST. If your javaScript is Http PUT or DELETE, you will find this error

The requested resource does not support http method ‘OPTIONS’.

Most of the browser will send a Preflight Request before it sends the actual request. One of the conditions to skip the Preflight Request is “The request method is GET, HEAD, or POST”. if you search to solve it, you will find that most of the result is stating that you could add and remove some handler in web.config could help.

Options Handler in web config
Options Handler in the web config

Someone reported that it really solve the problem, but it does not work in my environment. I then also found out that there is another workaround and it really works for me. We now add some handling to the HTTP OPTIONS verb in BeginRequest method.

protected void Application_BeginRequest(object sender, EventArgs e)
{
   if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
   {
        //These headers are handling the "pre-flight" OPTIONS call sent by the browser
       HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
       HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
       HttpContext.Current.Response.AddHeader("Access-Control-Allow‌​-Credentials", "true");
       HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
       HttpContext.Current.Response.End();
    }
}

If you check in Fiddler, now the Server Application Web API is accepting the OPTIONS method and response to your client app that the is now ready to receive your PUT/DELETE call.

 

Leave a Reply