在 IIS 中运行 Web 应用程序时,HttpContext 为 NULL [英] HttpContext is NULL when running web app in IIS

查看:24
本文介绍了在 IIS 中运行 Web 应用程序时,HttpContext 为 NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个应用程序,都在同一台 Windows 机器上运行.一个应用程序是 IdentityServer4,另一个是我自己的 Web 应用程序(服务器端 Blazor 应用程序).

I have two application, both running on the same Windows machine. One application is IdentityServer4, and the other is my own web application (Server side Blazor app).

这两个 Web 应用程序都是使用 .NET Core 3.1 构建的.

Both web apps are build with .NET Core 3.1.

当我导航到我的网络应用程序时,我首先被重定向到我的 IdentityServer4 应用程序.我登录,然后我被重定向回我的网络应用程序.

When I navigate to my web app, I first get redirected to my IdentityServer4 app. I login, and after that I get redirected back to my web app.

登录成功,因为IdentitServer的日志没有错误.此外,我在 Blazor 网页上看到了某个 claim 值.我在 Blazor 页面中通过 CascadingAuthenticationState 显示此 claim.通过该路径,一切正常.

The login was successful, because there are no errors in the logs of IdentitServer. Also, I see a certain claim value on my Blazor webpage. I display this claim through CascadingAuthenticationState in my Blazor page. Through that path everything works fine.

但是,每当我尝试通过代码隐藏"文件中的 HttpContext 获取登录用户时,我都会返回 Null 引用.例如:

But, whenever I try to get the logged in user through HttpContext in my "code behind" files, I get a Null reference back. For example:

public UserService(IHttpContextAccessor httpContextAccessor)
{
    // HttpClient is NULL...
    var httpCtx = _httpContextAccessor.HttpClient;  
}

奇怪的是,当我在 Visual Studio 中本地运行我的应用程序时,一切正常.当我在 Visual Studio 中调试时,我看到 HttpContext 设置了我的所有用户数据.

The strange thing is, that it all works fine when I run my application locally in Visual Studio. When I debug in Visual Studio I see that the HttpContext is set with all my user data.

但是,由于某种原因,当我从 IIS 运行应用程序时,HttpContextNULL.

But, for some reason HttpContext is NULL when I run the app from IIS.

我该如何解决这个问题?

How can I solve this issue?

推荐答案

如果 HttpContext 空引用异常发生在部署到 Azure 应用服务或 IIS 之后,您可能忘记启用 WebSockets.

If the HttpContext null-reference exception happens after deployment to Azure App Services or IIS, you might have forgotten to enable WebSockets.

交易如下:

如果应用在带有 IIS 的 Windows 上运行:必须启用 WebSockets.

If the app runs on Windows with IIS: WebSockets must be enabled.

请参阅IIS/IIS Express 支持部分.

这似乎是一个您必须遵循的先决条件.在处理了相同的问题并决定从 Visual Studio 中将我的应用程序发布到 Azure 后,我最近才发现了这一点.在我这样做之后,Visual Studio 给了我一个很好的警告,告诉我在 Azure 应用服务上启用 WebSockets 协议.

It seems that this is a prerequisite that you have to follow. I only recently discovered this myself after dealing with the same issue and deciding to publish my app to Azure from within Visual Studio. After I did so, Visual Studio gave me a nice warning telling me to enable WebSockets protocol on the Azure App Service.

这篇关于在 IIS 中运行 Web 应用程序时,HttpContext 为 NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆