[英]MVC controller seems to be validating wrong AntiForgery token
I am trying to pass an AntiForgery token in the header of an Ajax request. 我正在尝试在Ajax请求的标头中传递AntiForgery令牌。 My JavaScript code looks like this:
我的JavaScript代码如下所示:
var tokenadr = $('form[action="/ServiceRequests/CreateRequest"] input[name="__RequestVerificationToken"]').val();
var token = tokenadr;
var headers = {};
var headersadr = {};
headers['__RequestVerificationToken'] = token;
headersadr['__RequestVerificationToken'] = tokenadr;
$.ajax({
type: 'POST',
dataType: 'json',
headers: headersadr,
cache: false,
url: "/ServiceRequests/CreateRequest",
processData: false,
contentType: false,
data: formdata,
success: function (response, textStatus, jqXHR) {
window.location = "/ServiceRequests/Details/" + response.id;
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
},
})`
My form looks like this: 我的表格如下所示:
@using (Html.BeginForm("CreateRequest", "ServiceRequests", null, FormMethod.Post, new { enctype = "multipart/form-data", id = "requestForm" }))
{
@Html.AntiForgeryToken()
The problem is that in my shared views folder, I have a partial login view with a form like this: 问题是在我的共享视图文件夹中,我有一个部分登录视图,其格式如下:
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
So when I call my controller method using the Ajax code above, I get a server error. 因此,当我使用上面的Ajax代码调用控制器方法时,出现服务器错误。 My request does go through if I delete the AntiForgery token from my Account LogOff form (the token values are different for each form).
如果我从“帐户注销”表单中删除了AntiForgery令牌(每个表单的令牌值都不同),我的请求就会通过。 How can I resolve this without deleting my account logoff token?
如何解决此问题而不删除我的帐户注销令牌?
Here is my controller: 这是我的控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateRequest()
{
Here is what I have mainly been going by: How to make ajax request with anti-forgery token in mvc 这是我主要经历的事情: 如何在mvc中使用防伪令牌发出ajax请求
I solved this. 我解决了 Before my ajax call, I was serializing my whole form.
在进行ajax调用之前,我正在序列化整个表单。 I changed:
我变了:
var other_data = $('form').serializeArray();
To this: 对此:
var other_data = $('#requestForm').serializeArray();
And now I am in business. 现在我在做生意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.