2

I need to keep some static data about the user, after he has logged into my ASP.Net MVC 4 website. Everything is hook up in Castle Windsor container.

The login process calls an Authentication service, which returns the user data, that is needed for processing and other servicecalls later in a session.

I have looked at this post: MVC Custom Authentication, Authorization, and Roles Implementation. But the problem is that it uses servicelocation in a static class, which is problematic.

How should i store userdata for use throughout the session in a setup like this?

EDIT: I'm using persistent cookies, so somehow i need to recreate my userdata, when a user returns to the site.

Community
  • 1
  • 1
jand187
  • 296
  • 3
  • 14

1 Answers1

3

In your LogOn method once you have authorized the user and retrieved the user details from the database you could store them in the session:

UserDetail details = ...
Session["user_details"] = details;

and later when you need them:

UserDetail details = Session["user_details"] as UserDetail;

As an alternativeyou couldwrite a custom MembershipProvider which will read this information from the session if present and if not it will query the database to retrieve it.

Another possibility is to have a custom Authorize attribute by overriding the AuthorizeCore method in which you could setup a custom principal containing the user details and reading the, from the session.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thank you for answering. Your solution works fine, in a simple scenario, but it will not work for mine (see my edit above). – jand187 Oct 11 '12 at 10:39
  • I don't think that storing this information for such a long time in a persistent cookie is a good approach. You could of course do it. You could use the data portion of the forms authentication cookie to serialize any details about the user you like. But IMHO storing it in session and querying the database if the data is not available in the session is also a good approach. – Darin Dimitrov Oct 11 '12 at 10:41
  • I don't want to store the info in a cookie. I want to keep the data throughout the session. If a user comes back to the site with a persistent cookie, I need to load the date back into the session state. The problem is that the service I use to get the data is registered in an IoC container (Castle Windsor). The approach i linked to used a service locator to get this service, but I don't like service location. – jand187 Oct 18 '12 at 10:53
  • What will happen if someone try to view same page in different browser, this Session["user_details"] will be replaced with new details ? – Lazy Programer Mar 19 '20 at 13:11