选项405(方法不允许)web api 2

我创建了一个web api 2,我正在尝试对它进行跨域请求但是我收到以下错误:

选项http://www.example.com/api/save 405(方法不允许)

我已经浏览了一下这个问题的大多数解决方案都说我需要从NuGet安装COR并启用它,所以我已经安装了包并标记了我的控制器

[EnableCors("*", "*", "*")] 

但这仍然没有解决问题。

我的ApiController只有以下Save方法:

 [ResponseType(typeof(int))] public IHttpActionResult Save(Student student) { if (ModelState.IsValid) { using (StudentHelper helper = new StudentHelper()) { return Ok(helper.SaveStudent(student)); } } else { return BadRequest(ModelState); } } 

这是我来自不同领域的js:

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

我还需要做些什么来实现这个目标吗?

通过nuget为您的项目安装CORS Web API包:

安装包Microsoft.AspNet.WebApi.Cors

在WebApiConfig中添加以下行:

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

确保您将OPTIONS作为web.config中允许的动词之一,并且它由默认处理程序处理。

  ...  ...    

最后,我通过更改ajax请求解决了这个问题。 我发现OPTIONS预检仅在某些情况下发送 – 其中一个是如果请求包含的Content-Type不是以下类型之一:

  • 应用程序/ x-WWW窗体-urlencoded
  • 多部分/格式数据
  • 纯文本/

因此,通过删除我的ajax请求中的content-type并将其更改为以下内容:

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

我能够让它运作起来。

此页面包含有关简单请求以及如何避免预检请求的有用信息

还可以尝试使用withcredentials ajax request选项

  $.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); } }); 

这个解决了我的问题

步骤1

安装Cors包Microsoft.AspNet.WebApi.Cors (右键单击解决方案>管理Nuget包>然后搜索Cors)

第2步

将此行放在WebApiConfig.cs文件中

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

将http:// localhost:3000更改为API调用方的地址