C# ValidateAntiforgeryToken在ASP.NET MVC中不使用Ajax

C# ValidateAntiforgeryToken在ASP.NET MVC中不使用Ajax,c#,json,ajax,asp.net-mvc,antiforgerytoken,C#,Json,Ajax,Asp.net Mvc,Antiforgerytoken,有这种看法: @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" })) { @Html.AntiForgeryToken() <div id='calendar'></div> <script src="~/Scripts/Services/Agenda.js" type="text/javascript"><

有这种看法:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
    <div id='calendar'></div>
    <script src="~/Scripts/Services/Agenda.js" type="text/javascript"></script>
}
然后调用此函数:

function dbUpdate(data, startTime, title) {
    let evento = JSON.stringify({
        'Data': data,
        'StartTime': startTime,
        'Title': title,
        '__RequestVerificationToken': token
    });

    $.ajax({
        type: "POST",
        url: 'Agenda/DbUpdate',
        data: evento,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            console.log("Response");
        },
        complete: function () {
            console.log("After");
        },
        failure: function (jqXHR, textStatus, errorThrown) {
            alert("HTTP Status: " + jqXHR.status + "; Error Text: " + jqXHR.responseText); // Display error message
        }
    });
}
-生成的Json示例:

  {
  "Data":"2020-0105T03:00:00.000Z",
  "StartTime":"8",
   "Title":"Sdf",
   "__RequestVerificationToken":"IMBfPM4YPyslt_89W6Kfu_Nmy6OW2-8I4n3fp42Figy__2gid3wY8gMC- 
   glB2o3Y6v6TCEG18nZXRPfLltU2RpOvoy-rMFIyo-uPA2XL4JcFF1aJfXix6RWkTI5l6Ewqhyu5jSQnszEOre2ZP-az3Q2"
  }
控制器是:

[HttpPost]
[AjaxAuthorize]
[ValidateAntiForgeryToken]
public async Task<JsonResult> DbUpdate(AgendaEvent compromisso)
{
    ...
    return Json("ok");
}
请注意,如果我创建的类没有_RequestVerificationToken,因此:

public DateTime Data { get; set; }
public string StartTime { get; set; }
public string Title { get; set; }
我收到一个错误404

但是,即使令牌存在于传递的数据中,也不会进行验证


怎么了?

根据lordvlad30的建议,错误是由以下行引起的:

let evento = JSON.stringify({
    'Data': data,
    'StartTime': startTime,
    'Title': title,
    '__RequestVerificationToken': token
});
具体来说,它不应该有JSON.stringify()语句。因此,正确的答案是:

let evento = {
    'Data': data,
    'StartTime': startTime,
    'Title': title,
    '__RequestVerificationToken': token
};

一切正常

你收到其他数据了吗?
JSON.stringify
将数据对象转换为字符串,我认为这是不必要的,只需将对象传递给AJAX方法:
data:{…}
而不是
data:{…}
此外,您不需要在
AgendaEvent
类中使用
\uu RequestVerificationToken
属性。@lordvlad30我已经尝试过不使用该属性,但结果相同。。。没有任何更改…您还可以从
ajax
参数中删除
contentType
dataType
。jQuery会自动检测它们(除非您需要非默认值,但JSON是默认值)。。。
let evento = JSON.stringify({
    'Data': data,
    'StartTime': startTime,
    'Title': title,
    '__RequestVerificationToken': token
});
let evento = {
    'Data': data,
    'StartTime': startTime,
    'Title': title,
    '__RequestVerificationToken': token
};