[英]ASP.NET Core 2.2 AntiForgeryToken with JSON.Stringify
[英]Json to ASP.NET MVC Controller parameter is null when JSON.stringify
我試圖通過向其發送JSON對象作為參數,通過MVC控制器獲取信息。
控制器方法如下所示:
public ActionResult GetLatestInfoLogs(InfoLogUserJson invoker, InfoLogUserJson affected) {
// code
}
我有一個服務器端模型,如下所示:
public class InfoLogUserJson {
public int id { get;set; }
public int personId { get;set;}
public int customerId { get;set; }
public int rootUserId { get;set; }
public string ip { get;set; }
public bool unknown { get;set; }
}
我有一個客戶端腳本,如下所示:
var InfoLogUser = function () {
this.id = ko.observable(0);
this.personId = ko.observable(0);
this.rootUserId = ko.observable(0);
this.customerId = ko.observable(0);
this.unknown = ko.observable(false);
this.ip = ko.observable(null);
}
InfoLogUser.prototype = (function() {
return {
toJSON: function() {
return {
personId: this.getPersonId(),
rootUserId: this.getRootUserId(),
customerId: this.getCustomerId(),
id: this.getId(),
unknown: this.getUnknown(),
ip: this.getIp()
}
}
}
}());
在javascript視圖模型中,我正在嘗試執行以下操作:
var infoLogUser = new InfoLogUser();
infoLogUser.personId(1234);
$.ajax({
url: '/Whatever/GetLatestInfoLogs',
data: {
invoker: JSON.stringify(infoLogUser.toJSON()),
affected: null
},
dataType: 'application/json; charset: utf-8',
type: 'GET',
success: function(_infoLogs) {
alert('yay');
}
});
在我的網絡日志中,得到以下信息:查詢字符串參數:
調用者:{“ personId”:1234,“ rootUserId”:0,“ customerId”:0:“ id”:0,“ unknown”:false,“ ip”:null}受影響:
但是,當它在MVC控制器中命中GetLatestInfoLogs方法時,調用者參數始終為null。 如果我從ajax請求中刪除JSON.stringify,則調用者參數不為null,但其中未設置任何值。
我真的不知道發生了什么,所以希望你們中的任何人都可能知道發生了什么? :)
嘗試這個
$.ajax({
url: '/Whatever/GetLatestInfoLogs',
type: 'POST',
data: {
invoker: JSON.stringify(infoLogUser),
affected: null
},
contentType: 'application/json',
success: function(_infoLogs) {
alert('yay');
}
});
更新
var data = {invoker: infoLogUser, affected: null};
$.ajax({
url: '/Whatever/GetLatestInfoLogs',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function(_infoLogs) {
alert('yay');
}
});
您無需為.toJSON()
方法創建自己的方法。
只需執行以下操作:
invoker: JSON.stringify(infoLogUser)
您還需要確保設置內容類型,即
contentType: 'application/json'
我還注意到您的數據類型應為:
dataType: 'json'
整個通話將變成:
var infoLogUser = new InfoLogUser();
infoLogUser.personId(1234);
$.ajax({
url: '/Whatever/GetLatestInfoLogs',
data: {
invoker: JSON.stringify(infoLogUser),
affected: null
},
dataType: 'json',
contentType: 'application/json',
type: 'GET',
success: function(_infoLogs) {
alert('yay');
}
});
更新時您需要更改有效的JSON invoker
與affected
為字符串即
data: {
"invoker": JSON.stringify(infoLogUser),
"affected": null
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.