在.net Core 中像以前那样的使用HttpContext.Current
2018-06-28 19:24
477 查看
1.首先我们要创建一个静态类
public static class MyHttpContext { public static IServiceProvider ServiceProvider; public static Microsoft.AspNetCore.Http.HttpContext Current { get { object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor)); Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext; return context; } } }
2: 然后在startup.cs文件中
在Configure方法 添加
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
3. 改写ConfigureServices方法
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp) { ///省n多代码
Models.MyHttpContext.ServiceProvider = svp
} 在Configure方法的参数中加IServiceProvider svp;并在方法体中加 Models.MyHttpContext.ServiceProvider = svp; 其中MyHttpContext和声明的静态类名是一样的;
在程序中使用存储session就可以用
Models.MyHttpContext.Current.Session.Set("key", "value");
当然也可以把类名MyHttpContext改成HttpContext这样在程序中就是Models.HttpContext.Current.Session.Set("key", “value”)和之前的asp.net使用时一样的;
相关文章推荐
- 在.net Core 中像以前那样的使用HttpContext.Current
- NET Core中怎么使用HttpContext.Current
- ASP.NET多线程下使用HttpContext.Current为null解决方案
- ashx中使用HttpContext.Current.Session ,出现未将对象引用设置到实例上[转]
- 使用Nginx代理,HttpContext.Current.Request.Url.Host.ToString()获取地址是原地址的问题。
- ASP.NET多线程下使用HttpContext.Current
- ashx中使用HttpContext.Current.Session ,出现未将对象引用设置到实例
- ASP.NET多线程下使用HttpContext.Current为null解决方案
- ashx中使用HttpContext.Current.Session ,出现未将对象引用设置到实例
- 在类中使用page对象用HttpContext.Current
- ashx中使用HttpContext.Current.Session ,出现未将对象引用设置到实例上
- HttpContext.Current.Cache使用文件依赖问题
- 在ASP.NET Core中怎么使用HttpContext.Current
- ashx中使用HttpContext.Current.Session ,出现未将对象引用设置到实例
- ASP.NET多线程下使用HttpContext.Current为null解决方案 2015-01-22 15:23 349人阅读 评论(0) 收藏
- ASP.NET 使用HttpContext.Current.Cache
- ASP.NET多线程下使用HttpContext.Current为null解决方案 2015-01-22 15:23 350人阅读 评论(0) 收藏
- 安全地使用HttpContext.Current
- ASP.NET多线程下使用HttpContext.Current为null解决方案
- abp项目中无法使用HttpContext.Current.Session[""]的问题