HTTP代码405(方法不允许),当我在ASP.NET WebAPI CORS中发送POST数据时
Web.config文件
调节器
[EnableCors(origins: "https://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: "https://domain/api/Clients", type: "POST", data: sendData, success: function (d) { $("#msg").html(d); console.log(d); } });
浏览器错误:
POST https://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: "https://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
上述就是C#学习教程:HTTP代码405(方法不允许),当我在ASP.NET WebAPI CORS中发送POST数据时分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1015248.html