c# - 选项 405(不允许的方法)web api 2

标签 c# asp.net-mvc cors asp.net-web-api2

我已经创建了一个 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/

相关文章:

c# - 根据 MSDN,为什么 .NET 类 System.String 现在在三个不同的程序集中?

asp.net-mvc - 在事件 SignalR 连接期间更改用户身份 - 如何重新连接?

c# - 如何使用 MVC AJax.BeginForm 传递动态值

node.js - 使用 nginx 代理在 node.js 应用程序上启用 Cors

http - CORS 和 HTTP 基本身份验证

c# - 我应该明确断言计数还是结果?

c# - 在 System.Data.SqlCommand (C#) 中使用子查询 - 语法错误,在 SQL Server Mgmt Studio 中工作

c# - 如何在 ASP.NET 中动态创建的 TreeView 中添加 URL?

asp.net-mvc - 使用 $.ajax 发布 JSON 数据时如何提供 AntiForgeryToken?

ajax - Ajax可以跨域登录吗?