Access session variable in razor view .net core 2

前端 未结 3 1046
既然无缘
既然无缘 2021-02-04 01:45

I\'m trying to access session storage in a razor view for a .net core 2.0 project. Is there any equivalent for @Session[\"key\"] in a .net 2.0 view? I have not found a working e

3条回答
  •  悲哀的现实
    2021-02-04 01:56

    You can do dependency injection in views, in ASP.NET Core 2.0 :)

    You should inject IHttpContextAccessor implementation to your view and use it to get the HttpContext and Session object from that.

    @using Microsoft.AspNetCore.Http
    @inject IHttpContextAccessor HttpContextAccessor
    
    

    This should work assuming you have the relevant code in the Startup.cs class to enable session.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSession(s => s.IdleTimeout = TimeSpan.FromMinutes(30));
        services.AddMvc();
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSession(); 
    
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
    
        });
    }
    

    To set session in a controller, you do the same thing. Inject the IHttpContextAccessor to your controller and use that

    public class HomeController : Controller
    {
       private readonly ISession session;
       public HomeController(IHttpContextAccessor httpContextAccessor)
       {
          this.session = httpContextAccessor.HttpContext.Session;
       }
       public IActionResult Index()
       {
         this.session.SetString("isFiltered","YES");
         return Content("This action method set session variable value");
       }
    }
    

    Use Session appropriately. If you are trying to pass some data specific to the current page, (ex : Whether the grid data is filtered or not , which is very specific to the current request), you should not be using session for that. Consider using a view model and have a property in that which you can use to pass this data. You can always pass these values to partial views as additional data through the view data dictionary as needed.

    Remember, Http is stateless. When adding stateful behavior to that, make sure you are doing it for the right reason.

提交回复
热议问题