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

Web.config文件

              

调节器

  [EnableCors(origins: "http://domain/api/Clients", headers: "*", methods: "*")] public class ClientsController : ApiController { private ParaNewnergyEntities db = new ParaNewnergyEntities(); // GET: api/Clients public IEnumerable 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 } ); } 

阿贾克斯

  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和Option返回httpcode 200。

检查: 发布Web API 2应用程序后解决HTTP 405错误

MVC-Web API:405方法不允许


将数据传递给方法时存在问题,因为您尝试传递多个参数,您应该尝试如下所示

你需要做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(c); db.SaveChanges(); return Ok(c); } 

另请查看此处的post: http : //weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods