首页 > 解决方案 > IHttpContextAccessor.HttpContext 在生产环境中为空

问题描述

我有一个在开发和生产中表现不同的 Blazor Server 应用程序。问题是,在生产中HttpContext中,服务类中始终为空

所有服务类都派生自一个BaseService类。在构造函数中注入了所有依赖项。还有IHttpContextAccessor.

BaseService.cs

//Condensed down...
public abstract class BaseService
{    
    private IHttpContextAccessor _httpContextAccessor;      
    protected HttpContext HttpContext { get { return _httpContextAccessor.HttpContext; } }

    protected BaseService(IConfiguration configuration,
                          UserManager<MyProjectIdentityUser> userManager,
                          IHttpContextAccessor httpContextAccessor,
                          Repositories.MyDbContext dbContext,
                          ILogger<object> logger)
    {
        //...
        _httpContextAccessor = httpContextAccessor;
        //...
    }

    public async Task<MyProjectIdentityUser> GetUserAsync()
    {
        //Here is the HttpContext always null...
        var user = await UserManager.FindByIdAsync(HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value);
        return user;
    }
}

每当我需要某个服务类中的当前用户时,我都会调用var user = GetUserAsync();并获取它。

当我在 Visual Studio 中调试应用程序时,此实现完美运行,但在生产中,我无法访问HttpContext. 生产环境是 Ubuntu 18、Apache2 和 Cloudflare 的组合。

目前,我不知道从哪里开始寻找。生产中的其他一切也都有效。只要我不尝试访问 HttpContext。

标签: .net-coreapache2cloudflareblazor-server-sideasp.net-core-3.1

解决方案


正如我所怀疑的,代码没有问题,但环境有问题。它不可能是建立的 WebSocket 连接。这需要 Apache2 服务器中的一些配置

  1. 必须启用所有必需的模块。就我而言,rewrite proxy_wstunnel我必须启用。

    a2enmod rewrite    
    a2enmod proxy_wstunnel
    
  2. 应用程序的 .conf

    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:5000/
    ProxyPassReverse / http://127.0.0.1:5000/
    
    RewriteEngine on
    RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
    RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
    RewriteRule /(.*) ws://127.0.0.1:5000/$1 [P]
    

现在HttpContext可用。


推荐阅读