应用服务上的httpcontextaccessor空引用,但不调试

时间:2019-11-29 23:23:33

标签: azure azure-web-sites core blazor

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

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

返回context.User.FindFirst(ClaimTypes.NameIdentifier).Value;

我该怎么办才能使appcon服务中的httpcontext为null而不是在本地计算机上的调试中?

1 个答案:

答案 0 :(得分:1)

至少在大多数情况下,HttpContext在Blazor Server App中不可用。您不应尝试访问它,也不应使用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对象和授权组件(例如AuthorizeView,AuthorizeRouteView和CascadingAuthenticationState)访问Blazor Server App中的身份验证状态。