httpcontextaccessor应用服务上的null引用,但未调试

问题描述 投票:0回答:1

我有一个无法解释的怪异问题。

我在Blazor Server Side应用程序中有一个帮助程序类,该类为我的应用程序提供arb功能。我添加了services.AddHttpContextAccessor();在启动时,

在我的助手类中声明

public GlobalHelper(IHttpContextAccessor accessor, 
            IOptions<AzureADB2COptions> azureAdB2COptions,
            IConfiguration configuration

           )
        {
            _accessor = accessor;
            AzureAdB2COptions = azureAdB2COptions.Value;
            Configuration = configuration;

        }

然后有一个返回用户标识的函数:

 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。这行:

返回上下文。User.FindFirst(ClaimTypes.NameIdentifier).Value;

我可能会做错什么,以便在应用程序服务中httpcontext为null而不在本地计算机上的调试中?

azure azure-web-sites core blazor
1个回答
0
投票

至少在大多数情况下,HttpContext在Blazor Server App中不可用。您不应尝试访问它,也不应使用IHttpContextAccessor。在这里阅读更多:https://github.com/aspnet/AspNetCore/issues/14090https://github.com/aspnet/AspNetCore/issues/13903https://github.com/aspnet/AspNetCore/issues/12432#issuecomment-534315513https://github.com/aspnet/AspNetCore/issues/5330#issuecomment-413928731

注意:您可以根据需要通过身份验证状态提供者对象和授权组件(例如AuthorizeView,AuthorizeRouteView和CascadingAuthenticationState)访问Blazor Server App中的身份验证状态。>>

© www.soinside.com 2019 - 2024. All rights reserved.