How to Get the Value of a Session Variable Inside a Static Method

How can I get the value of a session variable inside a static method?

HttpContext.Current.Session["..."]

HttpContext.Current gets you the current ... well, Http Context; from which you can access: Session, Request, Response etc

Access Session values from static properties of static class

public class MyClass
{
public static string var2
{
get { return (string)System.Web.HttpContext.Current.Session["KEY_VAR2"]; }
set { System.Web.HttpContext.Current.Session["KEY_VAR2"] = value; }
}
}

Store session variable in action filter or static method

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.

Static class and Session variables

In short, I believe the answer is yes, however you should avoid having hard-coded dependencies in non-factory methods... Consider accepting a HttpSessionState or at the very least a HttpContext object to act on, like so:

public static int GetUserId(HttpContext context)
{
if(IsUserLoggedIn())
{
return Convert.ToInt16(context.Session["user"]);
}
return 0;
}

You should, however, likely be using the built in IPrincipal (User) property on the HttpContext, IMHO.

php how to: save session variable into a static class variable

From the PHP manual:-

Like any other PHP static variable,
static properties may only be
initialized using a literal or
constant; expressions are not allowed.
So while you may initialize a static
property to an integer or array (for
instance), you may not initialize it
to another variable, to a function
return value, or to an object.

You say that you need your session variables to be stored globally? They are $_SESSION is what is known as a "super global"

<?php

class utilities {
public static $color = $_SESSION['color']; //see here

function display()
{
echo $_SESSION['color'];
}
}

utilities::display(); ?>

Fetching session attributes from static methods

No, it's OK. And it is really thread safe. But from other side you should understand that it will be available only within HTTP Request Thread and from Spring MVC environment.

From other side, if you want to get that attribute from your @Controller or @Service you always can inject session there:

@Controller
class MyController {

@Autowired
private HttpSession session;

}


Related Topics



Leave a reply



Submit