c# - .Net Core ValidateAntiForgeryToken 抛出 web api 400 错误

标签 c# asp.net-core .net-core asp.net-core-webapi antiforgerytoken

Visual Studio 2017 与 Web Api 使用 .net Core 1.1 我正在使用,但我收到 400 错误请求错误。

各方面都出现错误:

  1. 角度 http
  2. fiddler
  3. postman
  4. 肥皂用户界面
  5. 招摇

POST 请求上的 ASP.NET Web API“400 错误请求”

[HttpPut]
//[ValidateAntiForgeryToken]
public IActionResult Put([FromBody]VeteranInteraction sessionTracker)
{ //.... } 

为什么会这样?

ValidateAntiForgeryToken 是问题所在,如果我将其注释掉就可以了。

最佳答案

您必须在每个请求上发送防伪 token

 var arr = { City: 'Tehran', Age: 25 };
    $.ajax({
        url: "@Url.Action("SaveAccess", "Access")",
        type: 'POST',
        data: JSON.stringify(arr),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        beforeSend: function (request) {
            request.setRequestHeader("RequestVerificationToken", $("[name='__RequestVerificationToken']").val());
        },
        success: function (msg) {
            alert(msg);
        }
    });

关于c# - .Net Core ValidateAntiForgeryToken 抛出 web api 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46189141/

相关文章:

c# - span<T> 和流

c# - 记录桌面保存每 30 分钟

asp.net-mvc - DbContext.OnConfiguring 没有被调用并且在 ASP.NET Core 中表现得很奇怪

c# - 无法在 Visual Studio 2019 16.2 中加载文件或程序集 Microsoft.VisualStudio.Coverage.Analysis

.net-core - .NET Core 3.1 Web session 超时

c# - 如何通过手动验证使 MobileNo、EmpOfficeCode 等实体在 EF core Razor 页面中唯一

c# - 使用 WPF 创建搜索框

c# - 在 ASP.NET Core 2 中获取 "SessionOptions.CookieName is obsolete"

c# - ConcurrentQueue 与 Queue + 锁的性能对比

c# - 如何在 ASP.Net Core 中使用 Google.Protobuf.WellknownTypes.Struct