OPTIONS 405(不允许的方法)网页API 2 [英] OPTIONS 405 (Method Not Allowed) web api 2
问题描述
我已经创建了一个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:
的选项 http://www.example.com/api/save 405(不允许的方法) 的
OPTIONS http://www.example.com/api/save 405 (Method Not Allowed)
我有一个看看周围,这个问题很分辨率说,我需要从安装的NuGet CORS并启用它,所以我已经安装了软件包,标志着我与
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
只有以下保存
方法:
[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请求解决了这个。我发现,在选项
preflight只在某些情况下发送 - 其中之一是,如果请求包含内容类型
不在以下类型之一:
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:
- 应用程序/ x-WWW的形式urlen codeD
- 的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);
}
});
我能得到它的工作。
I was able to get it working.
此页面有关于简单的请求和有用的信息如何避免preflight请求
这篇关于OPTIONS 405(不允许的方法)网页API 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!