问题描述
我已经创建了一个 web api 2 并且我正在尝试对其进行跨域请求,但是我收到以下错误:
I have created a web api 2 and I'm trying to do a cross domain request to it but I'm getting the following error:
OPTIONS http://www.example.com/api/save 405(不允许的方法)
我环顾四周,大多数解决此问题的方法都是说我需要从 NuGet 安装 COR 并启用它,因此我已经安装了该软件包并用
I have had a look around and most resolutions for this problem are saying that I need to install CORs from NuGet and enable it so I have installed the package and marked my controller with
[EnableCors("*", "*", "*")]
但这仍然没有解决问题.
But this still hasn't resolved the problem.
我的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:
This is my js from a different domain:
$.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);
}
});
我还需要做些什么来启用此功能吗?
Is there something else I need to do to enable this?
推荐答案
最后我通过改变ajax请求解决了这个问题.我发现 OPTIONS
预检仅在某些情况下发送 - 其中之一是如果请求包含不是以下类型之一的 Content-Type
:
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
- 文本/纯文本
因此,通过删除我的 ajax 请求中的内容类型并将其更改为以下内容:
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);
}
});
我能够让它工作.
这篇关于选项 405(不允许的方法)web api 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!