.NET CORE 3 中已经没有HttpContext.Current,如果要使用,需要扩展IHttpContextAccessor来达到使用的目的。
1、扩展
namespace System.Web { public static class HttpContext { private static IHttpContextAccessor _contextAccessor; public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext; internal static void Configure(IHttpContextAccessor contextAccessor) { _contextAccessor = contextAccessor; } } public static class StaticHttpContextExtensions { public static void AddHttpContextAccessors(this IServiceCollection services) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app) { var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>(); HttpContext.Configure(httpContextAccessor); return app; } } }
本例中,我们将扩展类放在System.Web命名空间中,主要是和以前的.Net Framework 保持一致,便于项目的迁移。
2、在Startup中注入
public void ConfigureServices(IServiceCollection services) { services.AddSession(); services.AddHttpContextAccessors(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseStaticHttpContext(); app.UseSession(); }
3、如果在使用过程中,出现 HttpContext.Current.Session.Id 随页面刷新而改变的情况,但是又不需要它改变,可以在写入Session前,随便写入一些值,如:
HttpContext.Current.Session.SetString("useri","dokeodkdmslsl");
这样就可以保证当前会话的 Session.Id 唯一,不受页面刷新而改变!