【问题标题】:IHttpContextAccessor.HttpContext is null in in production environmentIHttpContextAccessor.HttpContext 在生产环境中为空
【发布时间】:2020-01-05 21:51:37
【问题描述】:

我有一个 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-core apache2 cloudflare blazor-server-side asp.net-core-3.1


【解决方案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 可用。

【讨论】:

    猜你喜欢
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    相关资源
    最近更新 更多