首页 > 解决方案 > 如何在 .net core 2.2 中使用此代码(HttpContext.Request.Current.Session[key])

问题描述

我无法在 .net core 2.2 版本 HttpContext.Current.Session["key"] 中使用此代码

HttpContext.Current.Session["key"]

HttpContext.Current.Session["key"]

标签: .net-core

解决方案


在 .NET Core 中不再有静态HttpContext.Current,因为 .NET Core 有一个在 ASP.NET Core 内部使用的内置依赖注入系统。

如果您的代码在通常的 HTTP 请求范围内(中间件、控制器、视图等),则HttpContext当前 HttpContext 有一个可用的属性。否则,您可以使用IHttpContextAccessor(由 DI 注入)访问 HTTP 上下文。

您可以在此处找到所有详细信息:https ://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-2.2

如果您有 HttpContext 但 Session 为空,则必须启用 Session:https ://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2#session -状态


推荐阅读