OPTIONS 405 (Method Not Allowed) web api 2

心不动则不痛 提交于 2019-11-28 07:25:30

Via nuget make the installation of the CORS web API package for your project:

Install-Package Microsoft.AspNet.WebApi.Cors

In WebApiConfig add the following lines:

var cors = new EnableCorsAttribute ("*", "*", "*");
config.EnableCors (cors);

Ensure that you have OPTIONS as one of the allowed verb in your web.config and that it's being handled by the default handler.

<system.web>
...
  <httpHandlers>
  ... 
    <add path="*" verb="OPTIONS" type="System.Web.DefaultHttpHandler" validate="true"/>
    <add path="*" verb="TRACE" type="System.Web.DefaultHttpHandler" validate="true"/>
    <add path="*" verb="HEAD" type="System.Web.DefaultHttpHandler" validate="true"/>

This one solved my problem

Step 1

Install the Cors package Microsoft.AspNet.WebApi.Cors (Right Click Solution > Manage Nuget Package > And Then Search for Cors)

Step 2

put this line in the WebApiConfig.cs file

public static void Register(HttpConfiguration config)
{
    config.EnableCors(new EnableCorsAttribute("http://localhost:3000", headers: "*", methods: "*"));        
    .
    .
    .        
} 

Change http://localhost:3000 to the address of the API Caller

In the end I have solved this by changing the ajax request. I found out that the OPTIONS preflight is only sent in certain situations - one of them being if the request contains a Content-Type that is not one of the following types:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

So by removing the content-type in my ajax request and changing it to the following:

$.ajax({
    type: "POST",
    crossDomain: true,
    data: student,
    dataType: 'json',
    url: 'http://www.example.com/api/save',
    success: function (result) {
        console.log(result);
    }
});

I was able to get it working.

This page has useful information about simple requests and how to avoid preflight requests

Also try using the withcredentials ajax request option

    $.ajax({
     type: "POST",
     crossDomain: true,
     data: JSON.stringify(student),
     withCredentials: true,
     url: 'http://www.example.com/api/save',
     contentType: "application/json",
     success: function (result) {
      console.log(result);
     }
   });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!