Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store session variable in action filter or static method

Right now I am using a session variable to store a boolean value which I then use in my views. I know that HttpContext.Session[] variables are static, but does that mean I need to store them in a static method, or can I keep them in my action filter and call them directly from there?

Controller:

public class AuthorizationFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        // If not authorized, redirect to login page
        if (true)
        {
            authorized = false;
            filterContext.HttpContext.Session["authorized"] = authorized;


            filterContext.Result = new RedirectResult("https://www.website.com");
        }
        else
        {
            filterContext.HttpContext.Session["authorized"] = authorized;
        }
...

View:

@{var authorized = (bool)Session["authorized"];}
@if (authorized != null)
{
    if (authorized == true)
    {
        <li><a href="/">Download</a></li>
    }  
}

Should I be storing my session variables in static methods like below and calling them, instead of what I do above?

    public static bool Authorized(){
        return (bool)HttpContext.Current.Session["authorized"];
    }
like image 493
Keven Avatar asked Apr 16 '26 22:04

Keven


2 Answers

Yes, you can call Session variable like you did with no problems.

By the way,

@{var authorized = (bool)Session["authorized"];}

would throw an exception if Session["authorized"] == null.

UPDATE:

Common utility functions are often made static, because they're easy to use that way (don't need to create class instance each time you want to use functionality).

System.Web.HttpContext.Current.Session object (gets the same HttpSessionState object as wrapped by System.Web.Mvc.ActionExecutingContext) is available for the current HTTP request from anywhere in your application. It does not need to specifically belong to a static method. It could if you wanted to, but it does not have to.

like image 77
nomad Avatar answered Apr 19 '26 11:04

nomad


You are doing it the correct way. You should use the Session variable directly. No need to use a Static method. Session variables are available for that user session. They are not static variable(i.e. Class level variables)

like image 36
Adarsh Shah Avatar answered Apr 19 '26 11:04

Adarsh Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!