views:

57

answers:

2

I want to keep track of User Sessions within my MVC webapp. I know I am doing something wrong because the flow of the programming seems kind of chaotic. Any suggestions? At this point I am trying to verify Session every time I hit a different controller.

    private void VerifiedUserSession()
    {
        int? userID = (int?)Session["UserID"];
        if (userID.HasValue)
        {
            IUsersRepository userRepository = new SQLUserRepository();
            _user = userRepository.GetUser(userID.Value);
        }
        //TODO: Need to create a response for where the session is empty or null;
    }
+2  A: 

You should consider the Authorize attribute if you're trying to authenticate/authorize users.

You can implement a BaseController that has a User property and have your controllers extend from it. This way you'll only need this code once.

Additionally, you can override the BaseController's OnActionExecuting method. Within this method, if you can check for an existing User session and, if it doesn't exist, you can set the filterContext.Result property (to anything) to prevent the action from executing. You should probably forward to a login page or something at this point.

David Andres
+1 - Ultimately, any kind of filter attribute is a good solution for the OP's pattern.
womp
@womp: I was close to suggesting Model binding for no apparent reason, but I stopped myself!
David Andres
A: 

I think this is the similar question that I answered recently: http://stackoverflow.com/questions/1710875/better-way-of-doing-strongly-typed-asp-net-mvc-sessions/1711120#1711120

queen3