Access session variable in razor view .net core 2

前端 未结 3 1042
既然无缘
既然无缘 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
    <script>
       var isFiltered = '@HttpContextAccessor.HttpContext.Session.GetString("isFiltered")';
       alert(isFiltered);
    </script>
    

    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.

    0 讨论(0)
  • 2021-02-04 02:04

    As others have mentioned, I think the real solution here is not to do this at all. I thought about it, and while I have a good reason for using the session, since the razor tags are only useful for the initial page load anyway it makes more sense to just populate the view model in the controller with the stored session values.

    You can then pass the view model with the current session values to your view, and access your model instead. Then you don't have to inject anything into your view.

    0 讨论(0)
  • 2021-02-04 02:05

    put this at the top of the razor page

    @using Microsoft.AspNetCore.Http;
    

    then you can easily access session variables like that

    <h1>@Context.Session.GetString("MyAwesomeSessionValue")</h1>
    

    if you get null values , make sure you include that in your Startup.cs

    & make sure that options.CheckConsentNeeded = context is set to false

    For more information about CheckConsentNeeded check this GDPR

    public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    //options.CheckConsentNeeded = context => true;
                    options.CheckConsentNeeded = context => false;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    
    
                services.AddDistributedMemoryCache();
    
                services.AddSession(options =>
                {
                    // Set session timeout value
                    options.IdleTimeout = TimeSpan.FromSeconds(30);
                    options.Cookie.HttpOnly = true;
                });
            }
    

    Also make sure you are adding app.UseSession(); to your app pipeline in Configure function

    for more info about Sessions in Asp.net Core check this link Sessions in Asp.net Core

    tested on .net core 2.1

    0 讨论(0)
提交回复
热议问题