【问题标题】:ASP.NET HttpContext is null on AzureASP.NET HttpContext 在 Azure 上为空
【发布时间】:2022-01-20 11:10:31
【问题描述】:

我有一个托管在 Azure 上的 ASP.NET Blazor Web 应用程序。一切正常,除了一件小事。我使用IHttpContextAccessor.HttpContext,如Documentation 中所述。

    public class SessionService : ISessionService
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IUserService userService;

        public SessionService(
            IUserService userService,
            IHttpContextAccessor httpContextAccessor)
        {
            this.userService = userService;
            this.httpContextAccessor = httpContextAccessor;
        }

        public async Task<User> GetUser()
        {
            var userId = this.httpContextAccessor.HttpContext?.Items["userId"]?.ToString();
            
            if (userId == null)
            {
                return null;
            }

            if (!int.TryParse(userId, out var parsedUserId))
            {
                return null;
            }

            return await this.userService.Get(parsedUserId);
        }

        /// <inheritdoc />
        public async Task AuthenticateUser()
        {
            if (this.httpContextAccessor.HttpContext == null)
            {
                return;
            }

            // Authentication Logic
            // ...

            this.httpContextAccessor.HttpContext.Items["userId"] = authenticatedUser.id;
        }
    }

我稍后将这段代码称为:

var user = await sessionService.GetUser();
if (user == null)
{
   await sessionService.AuthenticateUser();
   user = await sessionService.GetUser();
}

到目前为止,这适用于我测试过的每台本地机器。我是在 Release 还是 Debug 中构建它并不重要。所有数据都已正确加载,我可以检索当前登录用户的 ID。

无论如何,如果我将应用程序发布到 azure,HttpContext 始终为空。我现在已经多次检查文档,但找不到任何将我推向正确方向的东西。我需要配置一些东西来专门使用 HttpContext 吗?

【问题讨论】:

    标签: asp.net blazor-server-side httpcontext


    【解决方案1】:

    您需要注入AuthenticationStateProvider 以从图表中获取信息,请不要使用IHttpContextAccessor 因为它存在安全问题,您可以在microsoft doc 中阅读更多相关信息。
    如何使用AuthenticationStateProvider
    在 blazor 页面中注入 AuthenticationStateProvider 如下:

    [Inject]
    public AuthenticationStateProvider AuthenticationState { get; set; }
     
    protected override async Task OnInitializedAsync()
    {
      var AuthSate = await AuthenticationState.GetAuthenticationStateAsync();
      var user = AuthSate.User;
    } 
    

    【讨论】:

    • 谢谢!我想我为自己过于复杂了。我已经在使用 AuthenticationState 来获取当前登录用户的身份名称。出于某种奇怪的原因,我认为将这些数据准确地存储在 cookie 中可能是个好主意。无论如何,正如我刚刚意识到的那样,当我阅读您的答案时,这没有任何意义,因为我实际上可以直接访问 AuthenticationState。
    猜你喜欢
    • 2020-09-22
    • 2010-09-18
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    相关资源
    最近更新 更多