的ASP.NET Web API 2 - POST / jQuery的 [英] ASP.NET Web API 2 - POST / jQuery
问题描述
我想发布一个对象所在的服务器,我使用的Web API 2,code如下:
$。阿贾克斯({
缓存:假的,
键入:POST,
网址:/ API /员工
数据:{雇员:1},
成功:函数(结果){
的console.log(雇员保存成功);
},
错误:功能(结果){}
});
至于网页API:
公共类EmployeesController:ApiController
{
// POST API /<控制器与GT;
公共无效后([FromBody]员工价值)
{
}
}公共类员工
{
公众的Int32雇员{搞定;组; }
公共字符串名字{获得;组; }
公共字符串名字{获得;组; }
公共字符串JOBTITLE {搞定;组; }
公众的DateTime出生日期{搞定;组; }
公共雇佣日期的DateTime {搞定;组; }
公共ReferenceData MaritalStatus {搞定;组; }
公众的Int32 VacationDays {搞定;组; }
公众的Int32 SickLeaveDays {搞定;组; }
公共小数工资{搞定;组; }
公共字符串熙{搞定;组; }
}
我结束了与服务器此响应
所请求的资源不支持HTTP方法POST
这是因为API路由如何工作的。这是/ API / NameOfController / NameOfMethod。控制器的名字是员工,你的方法的名字后。如果你想获得这个方法,你需要做的/ API /员工/发表。这就是为什么/ API /员工/ SaveEmployee当您更改方法名(每从昨天您的评论)工作正常。
I am trying to post an object to the server where I am using Web API 2. The code as follows:
$.ajax({
cache: false,
type: "POST",
url: "/api/Employees",
data: { EmployeeId: 1 },
success: function(result) {
console.log("employees saved successfully");
},
error: function(result) { }
});
As for the Web API:
public class EmployeesController : ApiController
{
// POST api/<controller>
public void Post([FromBody]Employee value)
{
}
}
public class Employee
{
public Int32 EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string JobTitle { get; set; }
public DateTime BirthDate { get; set; }
public DateTime HireDate { get; set; }
public ReferenceData MaritalStatus { get; set; }
public Int32 VacationDays { get; set; }
public Int32 SickLeaveDays { get; set; }
public decimal Salary { get; set; }
public string Cid { get; set; }
}
I am ending up with this response from server
The requested resource does not support http method 'POST'
That's because of how API routing works. It's /api/NameOfController/NameOfMethod. Your controller's name is Employee, and your method's name is Post. If you want to get to that method, you need to do /api/Employee/Post. That's why /api/Employees/SaveEmployee works fine when you change the method name (per your comment from yesterday).
这篇关于的ASP.NET Web API 2 - POST / jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!