0

Hi we developing web application using mvc4 and jquery mobile. In our each controller we created user session like below.

public class HomeController : BaseController { private static User CurrentUser;

 public ActionResult Index(string name) { CurrentUser = (User)Session["CurrentUserSession"]; return View(); } public ActionResult UserDetaiks() { string username = CurrentUser.UserFName; return View() } 

}

 Above we created object for User model and assigned session value in index method. But the value in CurrentUser is lost once i entered UserDetails. So i Used static while creating object. My question is it correct? or anyother way is there. Please guide me. 

Thanks guys One more Doubt,

I used below code in form authenticate.

 HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); var s = new System.Web.Script.Serialization.JavaScriptSerializer(); User obj = s.Deserialize<User>(authTicket.UserData); UserInformation CurrentUser = new UserInformation(obj.UserID); CurrentUser.UserId = obj.UserID; CurrentUser.FirstName = obj.UserFName; CurrentUser.LastName = obj.UserLName; CurrentUser.roles = obj.SecurityGroupName; CurrentUser.DefaultWarehouseId = obj.DefaultWhseIdentity; eg:14 HttpContext.Current.User = CurrentUser; } **Here User can Change CurrentUser.DefaultWarehouseId later like CurrentUser.DefaultWarehouseId = 16. but when i leave the method. It again getting value 14. Now i can code so CurrentUser.DefaultWarehouseId will be 16 through out app one i changed, Please guide me.** 
6
  • 1
    why are you creating it global you can fetch it from Session in the action locally when required Commented Jun 26, 2014 at 6:07
  • Also, there is no CurrentUser, if you visit details directly, without visiting Index first, because there is no assignment happening. Commented Jun 26, 2014 at 6:09
  • Did you try this with two different users? Using static won't work. Commented Jun 26, 2014 at 6:11
  • Keep in mind that static is not per-request. It's actually shared through the life-time of your application pool. In short, don't do it. Commented Jun 26, 2014 at 6:16
  • Please do not extend your question after your initial problem has been solved. If you have other issues, please open up seperate question for it Commented Jun 26, 2014 at 6:55

4 Answers 4

1

Since there is no guarantee, that the Index Method will be called before the UserDetails method, I wouldn't use a static variable to store the User. Instead each controller method should get the User from the session as required.

Sign up to request clarification or add additional context in comments.

4 Comments

but if i fetch User from the session as required. then i forced to write lot of redundant code. Future change will be very difficult.
You could place some code into a Baseclass (deriving from Controller), which retrieves the User from the Session and places it into a Property for instance. Then derive your UserController from your baseclass. Depending on your scenario, another option might be to use an ActionFilter.
thaks bro im going apply constructor approach. please see my updated post.
:im getting null exception inside constructor. I created my session in base controller. In home controller constructor it showing session is null.
1

In my opinion this question is better suited at CodeReview, but here we go:

Your code requires the user to visit Index first to assign a value to your currentuser variable. If a user visits details first, you'll get a NullReferencEception.

In the end you'd better be off, with assing the current user in the ActionMethod, if you do not need it in every method. If you need in every one of your actions, you can initialize it in your constructor

public class HomeController : BaseController { public ActionResult Index(string name) { User CurrentUser = (User)Session["CurrentUserSession"]; return View(); } public ActionResult UserDetails() { User CurrentUser = (User)Session["CurrentUserSession"]; string username = CurrentUser.UserFName; return View() } } 

OR:

public class HomeController : BaseController { private static User CurrentUser; public HomeController() { CurrentUser = (User)Session["CurrentUserSession"]; } /* ... */ } 

In any case you should check if the Session variable is not null. I suppose if there is no user logged in, this could get nasty.

3 Comments

You have tried to edit my answer. If you want to comment on it, use the comment function.
Im getting null exception inside constructor. I created my session in base controller. In home controller constructor it showing session is null.
You might want to read my last sentence again. If you did not store something in a session beforehand, it is natural that the session object is null.
0

Initialize in constructor :

public class HomeController : BaseController { private User CurrentUser; public HomeController() { CurrentUser = Session["CurrentUserSession"] as User; } public ActionResult Index(string name) { return View(); } public ActionResult UserDetaiks() { string username = CurrentUser.UserFName; return View() } } 

3 Comments

thanks lot. One more doubt. I used form authentication in my web application. In global.asax Application_PostAuthenticateRequest i used below code. UserInformation CurrentUser = new UserInformation(obj.UserID); CurrentUser.FirstName = obj.UserFName; CurrentUser.DefaultWarehouseId = obj.DefaultWhseIdentity.ToString(); HttpContext.Current.User = CurrentUser; Here User can change CurrentUser.DefaultWarehouseId whenevr he want. but im unable to assign value outside global.asx
:m getting null exception inside constructor. I created my session in base controller. In home controller constructor it showing session is null.
You cannot access the session in the constructor and you don't want to use static for this. It will blow up (or rather the CurrentUser will be overwritten) when multiple users are using it.
0

An alternative way to encapsulate the logic geting current user - using custom ModelBinder For example:

public class UserBinders : System.Web.Mvc.IModelBinder { private const string SessionKey = "CurrentUser"; public object BindModel(ControllerContext controllercontext, System.Web.Mvc.ModelBindingContext bindingContext) { HttpContextWrapper httpcontext = new HttpContextWrapper(System.Web.HttpContext.Current); string userLogin = httpcontext.User.Identity.Name var currentUser = (User)controllercontext.HttpContext.Session[SessionKey]; if (currentUser == null) { currentUser = context.GetUserByLogin(userLogin); controllercontext.HttpContext.Session[SessionKey] = currentUser; } return currentUser; } } 

Just declare the variable type User and get the current user.

public ActionResult UserDetaiks(User CurrentUser) { string username = CurrentUser.UserFName; return View() } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.