【问题标题】:User profile empty in HttpContext in azure web app天蓝色 Web 应用程序中 HttpContext 中的用户配置文件为空
【发布时间】:2021-03-05 10:37:20
【问题描述】:

我正在通过身份提供者 Auth0 使用 Azure Web 应用服务。 我得到了这个工作,但是每当我登录托管在 azure 上的网站时,用户配置文件都不会加载到 HttpContext 中。 这在 IIS Express 中本地工作。 知道我可能缺少什么吗?

这是我获取登录用户配置文件的代码:

[Inject]
    private IHttpContextAccessor HttpContextAccessor { get; set; }
    private string loginId;

    /// <summary>
    /// On initialized
    /// </summary>
    /// <returns></returns>
    protected override async Task OnInitializedAsync()
    {
        await LoadInvoiceTypes();
        this.loginId = HttpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;
    }

我在网站上做了一些登录,似乎 HttpContext 为空。

提前致谢!

【问题讨论】:

    标签: c# azure authentication azure-web-app-service auth0


    【解决方案1】:

    请先看看我的测试结果。

    下面是我的测试代码。

    public string test()
    {
        var obj = _httpContextAccessor.HttpContext;
        this.loginId = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;
            return loginId;
    }
    

    你可以通过gif看到我的测试结果。

    我尝试在Startup.cs 中添加services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();

    更多细节,你可以参考博客,它对我有用。

    Accessing HTTPContext in ASP.NET Core

    你也可以download my sample code to test it,希望我的回答可以帮助到你。

    【讨论】:

    • 嗨,Jason,感谢您的输入,但本地一切正常。当我发布到天蓝色时,HttpContext 是空的。
    【解决方案2】:

    显然建议在 blazor 中使用 AuthenticationStateProvider。 正如我预期的那样,这为我提供了 azure 中的登录用户。

        protected string loginId;
    
        [Inject]
        private AuthenticationStateProvider AuthProvider { get; set; }
    
        protected override async Task OnInitializedAsync()
        {
            var authState = await AuthProvider.GetAuthenticationStateAsync();
            this.loginId = authState.User.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;
            await base.OnInitializedAsync();
        }
    

    感谢您的意见。

    【讨论】:

    • 我建议你下次提问的时候,把问题写清楚,发帖问题从头到尾都没有提到blazor,在回答的时候也提到了,这是非常不友好的。
    猜你喜欢
    • 2016-10-12
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2015-09-25
    • 2021-01-10
    • 1970-01-01
    • 2014-10-14
    相关资源
    最近更新 更多