【问题标题】:httpcontextaccessor null reference on app service but not debug应用服务上的 httpcontextaccessor 空引用但不调试
【发布时间】: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


    【解决方案1】:

    HttpContext 在 Blazor 服务器应用程序中不可用,至少在大多数情况下。你不应该尝试访问它,也不应该使用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 应用程序中的身份验证状态,具体取决于您要执行的操作。

    【讨论】:

    • 很公平,我更喜欢使用 AuthStateProvider,但我还没有找到在自定义类中使用 authstateprovider 的方法。 authstateprovider 似乎很难在 DI 中使用。我的应用程序有时确实需要在视图之外使用 authstate(例如,我的自定义帮助程序类)。也建议不要直接使用authstateprovider,这样我就卡在了石头和硬地之间……
    • 感谢您的链接。所以我想问题是,将 vars 保存在 blazor 服务器端的最佳方法是什么。本地存储?
    猜你喜欢
    • 2022-01-14
    • 2023-02-21
    • 2015-04-14
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    相关资源
    最近更新 更多