首页 > 解决方案 > 使用 HttpContext 时 Blazor 抛出错误

问题描述

我想在用户打开网站时获取当前的 Windows 用户名。我的应用程序使用 Blazor 服务器端。要获取当前用户名,我添加了:

  1. 在 startup.cs 中:(
    services.AddHttpContextAccessor();在 ConfigureServices 下)
  2. 在剃须刀页面中:
    @inject IHttpContextAccessor httpContextAccessor
  3. 在剃刀页面方法中:
    string userName = httpContextAccessor.HttpContext.User.Identity.Name;

当我执行代码时,应用程序会抛出异常:

“发生错误。此应用程序在重新加载之前可能不再响应。”

仅当我在 IIS 上部署时才会收到此错误。在本地机器上它运行良好。

标签: asp.net-coreiisblazor

解决方案


如果您要更改该字符串

string userName = httpContextAccessor.HttpContext.User.Identity.Name

string userName = httpContextAccessor?.HttpContext?.User?.Identity?.Name??"Anonymous"

那么它可能会起作用。

这是因为您的 IIS 设置允许匿名访问,因此您的 Identity 对象为空。

您应该检查应用程序崩溃背后的内部异常,但这将是您的问题。您需要阻止 IIS 上的匿名访问以通过 Windows 身份验证。

要管理 IIS,请参阅此处https://stackoverflow.com/a/5458963/12285843


推荐阅读