开发者

Asp MVC, is session lost upon building solution?

I 'm writting an application in ASP.NET MVC. Basically I have some pages which require user authentication. Upon user logon, I keep the user row in a session. So in my controller I can access to the user.ID without making extra queries.

When project is in debug mode I can only change things in the views. Not in the controller.

If I 'm not debugging, I can build the solution, and see the changes I made without running the project (with F5). BUT, it looses all session variables I have.

So basically for every no-matter how small change in the controller, I have to logoff, logon to see my changes.

Are t开发者_如何学Chose normal behaviours?


Like Dan stated, this is normal behavior. To make it easier (and slightly more robust) is to change your code slightly. This is of course assuming that you are storing more than just the User ID in session since you can access the User ID via Controller.User.Identity.Name when they are authenticated. So you perform the lookup of the additional data in the session object and if it doesn't return null then use it. If it does return null, then look up the additional information again based on the User ID and store it in the session again. This is the approach I take for storing information from Active Directory and it works great.


Yes, this is a normal behaviour of ASP.NET as a whole not just MVC.

If you need to recompile (e.g a change in controller or business object) you will be in a new session when you run in debug. Like you say, only changes in views or pages (which do not require a recompile) will allow you to see changes in same session.

Kindness,

Dan


Recompiling will clear all the current session data. However it will not clear your authentication ticket, that's stored as a cookie, so there's a few things you can do to avoid this.

  1. If you only need to access the user id then use User.Indentity.Name

  2. If you only need basic user data for display purposes, such as the user's name, then you can store that in a session cookie. Warning: only do this for displaying data unless you encrypt the cookie data, plain text cookie data shouldn't be trusted.

  3. If your user data is more complex than that then access the data through a method that uses caching as suggested by Agent_9191

Add something like this to a base controller or extension method

protected UserData GetUserData() {
  UserData user = HttpContext.Session["User"] as UserData;
  if (user == null) {
    user = UserDataRepository.GetUser(User.Identity.Name);
    HttpContext.Session.Add("User", user);
  }
  return user;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜