Asp MVC, session loss after building decision?

I am writing an application in ASP.NET MVC. Basically, I have several pages that require user authentication. After logging in, I save the user string in the session. Therefore, in my controller, I can access user.ID without additional requests.

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

If I am not debugging, I can build a solution and see the changes that I made without starting the project (with F5). BUT , it loses all the session variables that I have.

So, in principle, for everyone it doesn’t matter how small changes are in the controller, I have to log out, log in to see my changes.

Is this normal behavior?

+3
source share
3 answers

As Dan said, this is normal behavior. To simplify (and slightly increase reliability), you need to slightly modify your code. This, of course, assumes that you store more than just the user ID in the session, as you can access the user ID through Controller.User.Identity.Namewhen they are authenticated. Thus, you search for additional data in the session object, and if it does not return null, then use it. If it returns null, then look again at the additional information based on the user ID and save it in the session again. This is the approach that I take to store information from Active Directory, and it works great.

+2

, ASP.NET MVC.

(, -), . , ( ) .

,

Dan

+2

. , cookie, , .

  • , User.Indentity.Name

  • , , cookie . : , cookie, cookie .

  • If your user data is more complex than this, then access the data using a method that uses caching, as suggested by Agent_9191

Add something like 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;
}
+1
source

Source: https://habr.com/ru/post/1722450/


All Articles