首页 > 解决方案 > .net core 3.1 如何添加HttpContext.Current和HttpContext.Current.Application[""]

问题描述

我在这里阅读了一些帖子,似乎 System.Web 和 HttpContext.Current 已从 .net 核心中删除。我在我的 startup.cs 中添加以下内容

services.addSingleton<IHttpContextAccessor, HttpContextAccesor>();

在将 HttpContext.Current 添加到我的班级时不起作用

在我的类库中,我将 Microsoft.AspNetCore.http 安装到我的依赖项中。我添加为 DI

public MyClass(IHttpContextAccessor _httpContextAccessor) {
  httpContextAccessor = _httpContextAccessor;
}

在我的cs代码中,旧代码以

if(HttpContext.Current != null && HttpContext.Current.Application["Test"] != null]) 

什么是替代品,到目前为止这不起作用

httpContextAccessor.HttpContext.Session != null 

Not sure what is the equivalent to HttpContext.Current.Application["Test"]

谢谢

标签: asp.netasp.net-core

解决方案


首先,在 Startup.cs 中注册服务,

services.AddHttpContextAccessor();

然后你可以在任何类中调用下面的代码,它取代了 HttpContext.Current

private HttpContext _httpContext => new HttpContextAccessor().HttpContext;

您可以使用_httpContext.Items[]代替应用程序。(生产前测试)


推荐阅读