HTTP 代码 405(不允许的方法),当我在 ASP.NET WebAPI CORS 中发送 POST 数据时

HTTP CODE 405 (Method Not Allowed), When I sent POST data in ASP.NET WebAPI CORS

Web.config

 <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
  </customHeaders>
</httpProtocol>
<handlers>
  <remove name="WebDAV"/>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

控制器

  [EnableCors(origins: "http://domain/api/Clients", headers: "*", methods: "*")]
public class ClientsController : ApiController
{
    private ParaNewnergyEntities db = new ParaNewnergyEntities();

    // GET: api/Clients
    public IEnumerable<Client> GetClient()
    {
        return db.Client.ToList();
    }
    [HttpPost]
    public IHttpActionResult PostClient(String Username, String Password)
    {
        Client c = new Client
        {
            Username = Username,
            Password = Password
        };

        db.Client.Add(c);
        db.SaveChanges();
        return Ok(c);
    }

WebApiConfig.cs

     public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.EnableCors();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }

Ajax

   var sendData={
            Username:"gx",
            Password:"gx"
        };
        $.ajax({
            url: "http://domain/api/Clients",
            type: "POST",
            data: sendData,
            success: function (d) {
                $("#msg").html(d);
                console.log(d);
            }
        });

浏览器错误:

  POST http://domain/api/Clients 405 (Method Not Allowed)

我可以通过GET方法得到API。我可以通过 POST 方法在没有 任何参数 的情况下从 API 获得响应,这很奇怪。否则,我刚收到 http 错误 405。

此外,我也从 DELETE 和 PUT 方法中得到 http 错误 405。只有 GET 和选项 return httpcode 200。

检查这个:Troubleshooting HTTP 405 Errors after Publishing Web API 2 Applications

MVC-Web API: 405 method not allowed


您将数据传递给您的方法的方式有问题,因为您正在尝试传递多个参数,您应该尝试如下

你ajax调用需要像

var client = {
    Username:"gx",
    Password:"gx"
}
$.ajax(
{
    url: "http://domain/api/Clients",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(client),
    success: function (result) {
        alert(result);
    }
});

你的 web api 方法会像这样

[HttpPost]
    public IHttpActionResult PostClient(Client client)
    {
        db.Client.Add(client);
        db.SaveChanges();
        return Ok(client);
    }

同时检查 post 此处:http://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods