Azure Web 应用程序中 HttpContext 中的用户配置文件为空

User profile empty in HttpContext in azure web app

我正在使用我的身份提供商 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 为空。

提前致谢!

请先看我的测试结果

下面是我的测试代码。

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<IHttpContextAccessor, HttpContextAccessor>();

更多细节,你可以参考博客,它适合我。

Accessing HTTPContext in ASP.NET Core

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

显然建议在 blazor 中使用 AuthenticationStateProvider。 正如我预期的那样,这给了我天蓝色的登录用户。

    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();
    }

感谢您的意见。