我的服务器上有一个具有ValidateAntiForgeryToken
属性的控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetHistory([FromBody] ChatMessageGetHistoryViewModel Input)
{
var userName = HttpContext.User.Claims.Where(c => c.Type == "UserName").Select(c => c.Value).SingleOrDefault();
var history = chatMessageData.GetAllBySessionId(Input.SessionId, userName);
var output = JsonConvert.SerializeObject(history);
return Ok(output);
}
我已经尝试过这种方法,但是到目前为止,我一直收到错误代码400。我尝试将
antiforgery
标记作为表单数据的一部分包含在内,但这也不起作用。<script>
$(document).ready(function () {
var token = $('input[name="__RequestVerificationToken"]', $('#__AjaxAntiForgeryForm')).val();
var SessionId = document.getElementById("Id").value;
var form_data = {
"SessionId": SessionId,
__RequestVerificationToken: token,
};
$.ajax({
url: "@Url.Action("GetHistory", @ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
if (output[i].Mine == true) {
p.setAttribute("class", "Sender Me");
q.setAttribute("class", "Message");
} else {
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
}
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
$('#MessageList').stop().animate({
scrollTop: $('#MessageList')[0].scrollHeight
}, 2000);
return false;
});
</script>
最佳答案
您必须通过RequestVerificationToken
请求将header
作为ajax
传递,如下所示:
$.ajax({
url: "@Url.Action("GetHistory", @ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
headers: { 'RequestVerificationToken': token }, // here have to set the token
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
if (output[i].Mine == true) {
p.setAttribute("class", "Sender Me");
q.setAttribute("class", "Message");
} else {
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
}
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
关于javascript - 带有JSON.Stringify的ASP.NET Core 2.2 AntiForgeryToken,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54423995/