.net-core - 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。
解决方案
正如我所怀疑的,代码没有问题,但环境有问题。它不可能是建立的 WebSocket 连接。这需要 Apache2 服务器中的一些配置
必须启用所有必需的模块。就我而言,
rewrite
proxy_wstunnel
我必须启用。a2enmod rewrite a2enmod proxy_wstunnel
应用程序的 .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
可用。
推荐阅读
- sql - 大数据集上 JSON 的 PostgreSQL 索引
- shell - 在 Hive 中声明时如何在变量中调用查询?
- c++ - 规范化用户输入的单词的大小写
- php - 超过 16 个项目时不保留 uksort() 数组顺序
- c# - 复杂请求的 Linq 问题
- r - 错误:安装 papaja 包并更新 R
- c - 如何使用 malloc 在 C 中初始化 char 数组?
- javascript - PHP JavaScript MYSQL:两个带有自动完成功能的搜索文件
- javascript - 在 JavaScript 中创建具有不同属性的多个标签
- javascript - 通过包含但不区分大小写的 DOM 中的特定单词搜索元素,使用 lower-case() XPATH 2.0 不起作用