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

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

问题描述

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

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

导航到Web应用程序时,首先要重定向到IdentityServer4应用程序.我登录,然后重定向到我的Web应用程序.

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

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

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

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

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

我该如何解决这个问题?

解决方案

如果部署到Azure App Services或IIS后发生HttpContext空引用异常,则您可能已忘记启用WebSockets./p>

这是交易:

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

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

似乎这是先决条件.在处理相同的问题并决定从Visual Studio内将我的应用发布到Azure之后,我才发现此问题.这样做之后,Visual Studio给我一个很好的警告,告诉我在Azure App Service上启用WebSockets协议.

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).

Both web apps are build with .NET Core 3.1.

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.

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.

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;  
}

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.

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

How can I solve this issue?

解决方案

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

Here is the deal:

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

See the IIS/IIS Express support section.

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天全站免登陆