简体   繁体   中英

HttpContext is null in ASP.Net Core 3.1?

As per https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1 I've added the appropriate code for sessions in Core 3.1

Here is are my modified sections for startup.cs

 // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {               
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.IsEssential = true;
        });

        services.AddControllersWithViews();

        services.AddDbContext<OrderContext>(op => op.UseSqlServer(Configuration.GetConnectionString("DatabaseConn")));
        services.AddDbContext<OrderContext>(op => op.UseSqlServer(Configuration.GetConnectionString("H20Connection"))); //Add  
        services.Configure<IISServerOptions>(options =>
        {
            options.AutomaticAuthentication = false;
        });

    }

    // 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.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseSession();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

In my controller i did as follows:

 public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly OrderContext _dbContext;
    public readonly IConfiguration _configuration;



    public HomeController(ILogger<HomeController> logger, OrderContext dbContext, IConfiguration iConfig)
    {
        _logger = logger;
        _dbContext = dbContext;
        _configuration = iConfig;

        if (HttpContext.Session.Get<List<Rate>>("Rates") == null)
        {
            HttpContext.Session.Set<List<Rate>>("Rates", GetRates());
        }
    }
  ...

But when i run this HttpContext is null.

Anyone know why is this happening?

Special thanks to @Nkosi for pointing out that HttpContext is not yet initialized in the constructor of my controller. I moved this to an action and it works now!

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM