我已经创建了一个 web api 2,我正在尝试对其进行跨域请求,但出现以下错误:
OPTIONS http://www.example.com/api/save 405 (Method Not Allowed)
我环顾四周,这个问题的大多数解决方案都说我需要从 NuGet 安装 COR 并启用它,所以我已经安装了包并将我的 Controller 标记为
[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 包:
Install-Package Microsoft.AspNet.WebApi.Cors
在 WebApiConfig 中添加以下行:
var cors = new EnableCorsAttribute ("*", "*", "*");
config.EnableCors (cors);
关于c# - 选项 405(不允许的方法)web api 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26649361/