【发布时间】:2017-02-01 22:03:24
【问题描述】:
首先,我只想说这里已经发布了很多类似的问题,但我已经尝试了所有的解决方案,但没有任何乐趣。
我有一个 MVC ApiController Action,其签名是:
public void Post([FromBody] Employee employee)
我尝试过使用或不使用 [FromBody]。
我的 Employee 类有 5 个基本类型的成员,int、string、string、string、double
我正在使用 jQuery Ajax 从单独的域(都在我的本地主机上使用 Cors)调用 Action,如下所示:
$.ajax({
url: "http://localhost:55555/api/Employees",
type: "POST",
headers: {
"Authorization": "Bearer " + sessionStorage.getItem("accessToken")
},
data: {
Id: 100,
FirstName: "Fred",
LastName: "Blogs",
Gender: "Male",
Salary: 100000
},
// ...
这绝对没问题。授权没有问题。 Controller 上的 Employee 对象填充了这些数据。但我想做的是以更“结构化”的方式发送数据。所以我的数据看起来像这样:
data: {
employee: employee
},
我已经尝试了所有我能想到的格式化员工的方法。指定所有组合:
contentType: "application/json; charset=utf-8",
dataType: "json",
结合不同的方式来“字符串化”我的员工对象:
var employee = {
Id: 100,
FirstName: "Fred",
LastName: "Blogs",
Gender: "Male",
Salary: 100000
};
employee = JSON.stringify({ "employee": employee });
employee = JSON.stringify(employee);
如果这是相关的(作为一个更简单的例子),我的 ApiController 上也有这个方法:
public void Delete([FromBody] int employeeId)
同样,我无法以“所需”方式传递employeeId。
我什至无法得到:
data: {
employeeId: 100
},
上班!?!
如果我将其更改为 [FromUri] 并在调用 Url 中指定“?employeeId=100”,我可以让 Delete 方法工作。
我希望我可以在不同的调用中更加一致,并始终以 JSON 格式传递一个“对象”。
有人有什么想法可以帮助我进步吗?
谢谢。
有关 Delete 调用的更多信息。
如果我使用 Postman,请删除身份验证要求,指定 Content-Type "application/json" 在 header 和 body 中的 employeeId = 100 中,Postman 返回:
{
"Message": "The request is invalid.",
"MessageDetail": "The parameters dictionary contains a null entry for parameter 'employeeId' of non-nullable type 'System.Int32' for method 'Void Delete(Int32)' in 'WebApi.Controllers.EmployeesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}
【问题讨论】:
标签: javascript jquery ajax asp.net-apicontroller