首页 > 解决方案 > 应用服务上的 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 为空,而不是在我的本地机器上的调试中?

标签: azureazure-web-app-serviceblazor

解决方案


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,具体取决于您要执行的操作。AuthorizeRouteViewCascadingAuthenticationState


推荐阅读