首先,讓我說剛纔已經發布的許多類似的問題,但我已經嘗試了所有的解決方案並且沒有快樂。將數據從jQuery Ajax調用傳遞給MVC ApiController操作正在丟失數據
我有一個MVC ApiController行動的簽名是:
public void Post([FromBody] Employee employee)
我帶或不帶[FromBody]試過。
我Employee類有基本類型,整型,字符串,字符串,字符串的5名成員,雙
我打電話從一個單獨的域的行動(包括使用一個Cors我的本地主機),使用jQuery的Ajax如下:
$.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);
萬一這與(作爲一個更簡單的例子),我也有這個方法對我的ApiControll呃:
public void Delete([FromBody] int employeeId)
再次,我無法通過「所需」的方式傳遞employeeId。
我甚至無法獲得:
data: {
employeeId: 100
},
工作!?!
我可以讓Delete方法工作,我將它更改爲[FromUri]並在調用Url中指定「?employeeId = 100」。
我希望我可以在不同的調用中保持一致性,並且始終以JSON格式傳遞'對象'。
有沒有人有任何想法可以幫助我進步?
謝謝。
有關刪除呼叫的更多信息。
如果我使用郵差,刪除要求身份驗證,指定內容類型的「application/JSON」在頭 和在主體EMPLOYEEID = 100,郵差返回:
{
"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."
}
我試過了。再次使用dataType/contentType的所有組合。該方法被調用,但Employee對象的所有屬性在ApiController Action中仍具有默認的null,0值。 –
嘗試添加'的contentType: '應用/ JSON的',數據類型: 「JSON」'你'$ .ajax'設置 – JohanP
仍然在服務器上的員工對象有默認值: VAR員工= { 編號:100, 名字:「Fred」, 姓氏:「博客」 性別:男性, 工資:100000 }; $阿賈克斯({ 網址: 「HTTP:// ..., 類型: 」POST「, 頭:{ 」授權「: 」承載「 + sessionStorage.getItem(」 的accessToken「) }, contentType:「application/json」, dataType:「json」, data:JSON.stringify({employee:employee}), –