Когда я отлаживаю его, свойство HttpContext IHttpContextAccessor в классе ApplicationContext всегда имеет значение null. Это приложение net core 3.1
publi c stati c class ApplicationContext {private stati c IHttpContextAccessor _httpContextAccessor;
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public static HttpContext Current => _httpContextAccessor.HttpContext;
}
ApplicationContext.cs
public static class HttpSessionHelper
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}
HttpSessionHelper.cs
public class RequestHandler
{
public void HandleIndexRequest()
{
// do something for the request
var message = "This is a much cleaner approach to access Session!";
ApplicationContext.Current.Session.Set<string>("message", message);
}
}
RequestHandler.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc();
services.AddSession();
services.AddHttpContextAccessor();
services.AddSingleton<RequestHandler>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseCookiePolicy();
app.UseSession();
ApplicationContext.Configure(app.ApplicationServices
.GetRequiredService<IHttpContextAccessor>());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{controller=Login}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
Startup.cs