locked
Check if a current session variable not null before actions are executed RRS feed

  • Question

  • User1300985299 posted

    Hi,

    I'm a beginning .Net developer and working in MVC on a basic rental solution.

    When a user opens the website he comes to the HomeController/Login page. Here he has to enter his last name and postal code. The code then checks whether or not the combo is in a customers table.

    If it is the customer object is stored in a httpcontext.session variable "loggedinuser". The website then redirect to a rental controller/overview action. 

    In the rental controller I want to apply an actionfilter which checks whether "loggedinuser" is null or empty. if yes the website has to redirect to Home/Logins again.

    I've been looking on internet and found some sollutions with usage of:

    var ctx = filtercontext.HttpContext;

    if(ctx.Session["loggedinuser"] !=null)

    However if I do that I get an error saying that indexing [ ] is not possible wit ISession.

    Can you help me out here?  How do I approach this and where do I store the actionclass?

    Tuesday, December 8, 2020 4:13 PM

Answers

  • User1686398519 posted

    Hi TinoS, 

    1. If your project is an ASP.NET MVC project, your code is correct.
    2. If your project is an ASP.NET Core MVC project, you need to install Microsoft.AspNetCore.Session first, and then enable session middleware in the Startup file.
      1. Startup.cs
        • The order of middleware is important. Call UseSession after UseRouting and before UseEndpoints.
        • public void ConfigureServices(IServiceCollection services)
          {
              services.AddDistributedMemoryCache();
              services.AddSession();
          }
          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
          {
              app.UseRouting();
              app.UseSession();
              app.UseEndpoints(endpoints =>
              {
                  endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Test66}/{action=Index}/{id?}");
              });
          }
      2. TestFilter
        •     public class TestFilter : ActionFilterAttribute
              {
                  public override void OnActionExecuting(ActionExecutingContext filterContext)
                  {
                      var value = filterContext.HttpContext.Session.GetString("loggedinuser");
                  }
              }
      3. Controller
        1.     public class Test66Controller : Controller
              {
                  public IActionResult Index()
                  {
                      HttpContext.Session.SetString("loggedinuser", "test");
                      return View();
                  }
                  [TestFilter]
                  public IActionResult Test()
                  {
                      return View();
                  }
              }
      4. You can click this link to learn more about Configure session state.
      5. Here is the result. 

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 9, 2020 9:43 AM

All replies

  • User475983607 posted

    You have not mentioned what framework you are using.  If ASP.NET not Core or .NET 5 then it's just...

    if(Session["MySessionKey"] == null)
    {
      //Session is null
      //Get values and set session
    }
    else 
    {
       //Session is not null
    }

    Reference documentation

    https://docs.microsoft.com/en-us/previous-versions/aspnet/ms178581(v=vs.100)

    I recommend using standard authentication/authorization libraries that come with MVC.  The libraries handle empty user session.

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/

    Tuesday, December 8, 2020 7:29 PM
  • User1686398519 posted

    Hi TinoS, 

    1. If your project is an ASP.NET MVC project, your code is correct.
    2. If your project is an ASP.NET Core MVC project, you need to install Microsoft.AspNetCore.Session first, and then enable session middleware in the Startup file.
      1. Startup.cs
        • The order of middleware is important. Call UseSession after UseRouting and before UseEndpoints.
        • public void ConfigureServices(IServiceCollection services)
          {
              services.AddDistributedMemoryCache();
              services.AddSession();
          }
          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
          {
              app.UseRouting();
              app.UseSession();
              app.UseEndpoints(endpoints =>
              {
                  endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Test66}/{action=Index}/{id?}");
              });
          }
      2. TestFilter
        •     public class TestFilter : ActionFilterAttribute
              {
                  public override void OnActionExecuting(ActionExecutingContext filterContext)
                  {
                      var value = filterContext.HttpContext.Session.GetString("loggedinuser");
                  }
              }
      3. Controller
        1.     public class Test66Controller : Controller
              {
                  public IActionResult Index()
                  {
                      HttpContext.Session.SetString("loggedinuser", "test");
                      return View();
                  }
                  [TestFilter]
                  public IActionResult Test()
                  {
                      return View();
                  }
              }
      4. You can click this link to learn more about Configure session state.
      5. Here is the result. 

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 9, 2020 9:43 AM