[英]OPTIONS 405 (Method Not Allowed) 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 中允许的动词之一,并且它由默认处理程序处理。
<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"/>
这个解决了我的问题
第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 Caller 的地址
最后我通过更改ajax请求解决了这个问题。 我发现了OPTIONS
预检只在某些情况下会发送-它们是如果请求包含一个Content-Type
不属于以下类型之一:
因此,通过删除我的 ajax 请求中的内容类型并将其更改为以下内容:
$.ajax({
type: "POST",
crossDomain: true,
data: student,
dataType: 'json',
url: 'http://www.example.com/api/save',
success: function (result) {
console.log(result);
}
});
我能够让它工作。
也尝试使用 withcredentials ajax 请求选项
$.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);
}
});
我正在从 angular 应用程序调用 .net Web API 并收到405 方法不允许错误。 我发现我在 angular http.post 中缺少标题选项。 因此,我在 angular 的 http 请求中添加了标头'Content-Type': 'application/json'
,这解决了我的错误并成功命中 wpi 操作。
因此,要解决该错误,请在WebAPIConfig
需要引用 ( System.Web.Http.Cors
) 中的 .net web api 中使用EnableCors
。 像这样:
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
并在 angular http 中添加标题。 希望它可以帮助某人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.