Blazor应用登出时POST请求未触发OnPostAsync问题排查
解决Blazor中POST请求登出返回400的问题
返回400错误的核心原因是ASP.NET Core默认对POST请求启用了防伪令牌(Anti-Forgery Token)验证,你的fetch请求未携带该令牌,导致后端拒绝请求。
以下是两种可行的解决方式:
方式一:携带防伪令牌发起请求(推荐,保证安全性)
步骤1:确保项目支持获取防伪令牌
如果是Blazor Server项目,先在Program.cs中注册IHttpContextAccessor:
builder.Services.AddHttpContextAccessor();
步骤2:在组件中获取并携带令牌
方式A:通过HttpContextAccessor获取令牌
@inject IHttpContextAccessor HttpContextAccessor @code { private async Task PerformLogout() { var antiForgeryToken = HttpContextAccessor.HttpContext?.Request.Cookies["XSRF-TOKEN"]; if (!string.IsNullOrEmpty(antiForgeryToken)) { await fetch('https://localhost:44300/Identity/Account/LogOut', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'RequestVerificationToken': antiForgeryToken } }); } } }
方式B:从页面隐藏字段获取令牌(适用于包含Razor页面的场景)
在页面中生成防伪令牌隐藏字段,再通过JS获取并携带:
@* 在Razor页面或组件中添加防伪令牌字段 *@ @Html.AntiForgeryToken() <script> async function logout() { const tokenElement = document.querySelector('input[name="__RequestVerificationToken"]'); if (tokenElement) { const token = tokenElement.value; await fetch('https://localhost:44300/Identity/Account/LogOut', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `__RequestVerificationToken=${encodeURIComponent(token)}` }); } } </script>
方式二:禁用防伪令牌验证(不推荐,降低安全性)
如果是测试场景或特殊需求,可以在LogoutModel上添加[IgnoreAntiforgeryToken]特性跳过验证:
[IgnoreAntiforgeryToken] public class LogoutModel : PageModel { public async Task<IActionResult> OnPostAsync() { await HttpContext.SignOutAsync(); return Redirect("/Identity/Account/Unauthorized"); } }
注意:该方式会关闭POST请求的防伪保护,可能导致CSRF攻击,生产环境请勿使用。
内容的提问来源于stack exchange,提问作者openshac
相关产品推荐
相关产品推荐

