【发布时间】:2020-03-25 11:20:20
【问题描述】:
我有一个无法解释的奇怪问题。
我的 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 类中的httpcontextaccessor 时得到一个nullreferenceexception。这一行:
return context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
我做错了什么导致应用服务中的 httpcontext 为空,而不是在我的本地机器上调试?
【问题讨论】:
标签: azure azure-web-app-service blazor