You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Blazor 8 InteractiveServer中实现防伪造?(6/7迁移场景)

Blazor 8 InteractiveServer 防伪造配置迁移问题

迁移背景与原配置

在Blazor 6/7 Server应用中,通过_Host.cshtml配置防伪造,代码如下:

@inject IAntiforgery Xsrf
// ...
<body>
    @{
        var initialTokenState = new InitialApplicationState
            {
                XsrfToken = Xsrf.GetAndStoreTokens(HttpContext).RequestToken,
                Cookie = HttpContext.Request.Cookies[".AspNetCore.Cookies"],
                RemoteIp = HttpContext.GetRemoteIpAddress(Logger)
            };
    }

迁移后遇到的问题

  • 将_Host.cshtml内容迁移至App.razor后,发现App.razor中没有HttpContext属性,无法沿用原方式获取防伪造令牌
  • 官方文档仅讨论了表单提交场景的防伪造支持,未提及页面渲染场景的配置方法
  • 运行无表单页面时触发以下错误:

InvalidOperationException: Endpoint /sitemap (/sitemap) contains anti-forgery metadata, but a middleware was not found that supports anti-forgery.
Configure your application startup by adding app.UseAntiforgery() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAntiforgery() must go between them. Calls to app.UseAntiforgery() must be placed after calls to app.UseAuthentication() and app.UseAuthorization().

疑问

Blazor 8的防伪造配置步骤与旧版本明显不同,但找不到对应的官方文档。我的应用仅从Blazor 6/7 Server渲染模式转为Blazor 8 InteractiveServer模式,并未配置端点,请问相关的配置文档在哪里?


内容的提问来源于stack exchange,提问作者David Thielen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 21:23:16