azure - 应用服务上的 httpcontextaccessor 空引用但不调试
问题描述
我有一个奇怪的问题,我无法解释。
我的 Blazor 服务器端应用程序中有一个帮助程序类,它为我的应用程序执行套利功能。我 services.AddHttpContextAccessor();
在启动时添加,
在我的助手类中声明它
public GlobalHelper(IHttpContextAccessor accessor,
IOptions<AzureADB2COptions> azureAdB2COptions,
IConfiguration configuration
)
{
_accessor = accessor;
AzureAdB2COptions = azureAdB2COptions.Value;
Configuration = configuration;
}
然后有一个函数来返回用户ID:
public string GetUserID()
{
var context = _accessor.HttpContext;
return context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
然后在我的页面中,我只想在按钮单击事件上首先显示它:
@inject Classes.GlobalHelper _helper
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
string currentCount = "test";
void IncrementCount()
{
var test4 = httpContextAccessor.HttpContext;
var authState = AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.Result.User;
if (user.Identity.IsAuthenticated)
{
try
{
currentCount = _helper.GetUserID().Result;
}
catch (Exception ex)
{
currentCount = ex.ToString();
}
}
else
{
Console.WriteLine("The user is NOT authenticated.");
}
}
}
如果我只是在本地调试,这很好。一旦我将它发布到 Azure 中的应用程序服务......我就会在 globalhelper 类中nullreferenceexception
访问。httpcontextaccessor
这一行:
return context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
我可能做错了什么,以至于应用程序服务中的 httpcontext 为空,而不是在我的本地机器上的调试中?
解决方案
HttpContext
至少在大多数情况下,在 Blazor Server 应用程序中不可用。您不应该尝试访问它,也不应该使用IHttpContextAccessor
. 在此处阅读更多信息:https:
//github.com/aspnet/AspNetCore/issues/14090
https://github.com/aspnet/AspNetCore/issues/13903
https://github.com/aspnet/AspNetCore/issues/12432# issuecomment-534315513
https://github.com/aspnet/AspNetCore/issues/5330#issuecomment-413928731
注意:您可以通过对象和AuthenticationStateProvider
授权组件(例如 )访问 Blazor Server 应用程序中的身份验证状态AuthorizeView
,具体取决于您要执行的操作。AuthorizeRouteView
CascadingAuthenticationState
推荐阅读
- angularjs - 在 Internet Explorer 11 中查看 PDF
- python - 如何从 json 查询中获取和打印特定数据?
- java - 如何合并两个ArrayList
- javascript - Javascript 变量在 obejct 中不起作用。但是上console.log
- python - matplotlib 中带有欧元符号的刻度
- c# - 如何使用扩展 WPF 工具包创建简单的饼图
- java - 总是/只添加一次到 Intent.ACTION_VIEW
- algorithm - 旅行推销员中的贪婪方法 VS 动态规划
- sass - 有没有根据窗口大小改变元素高度的好方法?
- json - Angular i18n json 文件中的自动比较检查