asp.net-core - 使用 HttpContext 时 Blazor 抛出错误
问题描述
我想在用户打开网站时获取当前的 Windows 用户名。我的应用程序使用 Blazor 服务器端。要获取当前用户名,我添加了:
- 在 startup.cs 中:(
services.AddHttpContextAccessor();
在 ConfigureServices 下) - 在剃须刀页面中:
@inject IHttpContextAccessor httpContextAccessor
- 在剃刀页面方法中:
string userName = httpContextAccessor.HttpContext.User.Identity.Name;
当我执行代码时,应用程序会抛出异常:
“发生错误。此应用程序在重新加载之前可能不再响应。”
仅当我在 IIS 上部署时才会收到此错误。在本地机器上它运行良好。
解决方案
如果您要更改该字符串
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
推荐阅读
- python - Facebook Ads API - 如何获取通过 JS Pixel 发送的自定义字段?
- pandas - Pandas 从 azure blob 存储 wasbs 路径读取文件
- python-3.x - 图像翻译算法 - 将 Python 算法翻译成 Julia 语言
- android - 仅为 android 仪器测试添加权限
- kotlin - 在 @Composable (Jetpack Compose) 中使用 get() 时出错
- visual-studio-code - 我不明白为什么我的#include 不是紫色的,即使我下载了我确定需要下载的东西
- python - 使用python更改图像中的颜色范围
- ruby-on-rails - 如何从 Vue.js 组件访问 Rails 实例变量?
- javascript - 有人可以提供一个不使用 React 的 JSX 的“hello world”示例吗?
- sqlite - 无法向 sqlite 表添加记录:数据库操作预计会影响 1 行,但实际上影响了 0 行