2

I work on an ASP.NET MVC4 solution. When the user is logged in, I would like to display his fullname (not the username provided in the login form). His fullname (firstname + lastname actually stored in the user table in my database) should be displayed in the top right corner.

For better performance, I don't want to query the database each time a request is done.

How to proceed?

  • Keeping the user information (firstname, lastname, ...) in a cookie?
  • Keeping the user information is a session variable for all the lifecycle of the application?
  • Keeping the user information in a 'Profile' like explained here: How to assign Profile values? (*)
  • Something else?

(*) I think this solution a little complex for the use I have.

Thanks.

Community
  • 1
  • 1
Bronzato
  • 9,438
  • 29
  • 120
  • 212

1 Answers1

1

I would use a cookie. It doesn't hog up any memory on your machine like Session, and it doesn't hit the database like Profile would. Just remember to delete the cookie when the user signs off.

Note that the Profile would hit the database server each time you make a request. As far as I know, Profile data is not cached anywhere on the web server (unless you have a custom profile provider).

Another reason why I like cookie: if you ever want to store any additional user information for fast access, like UserPrimaryKey, or any special user preferences, you can just store them as JSON in the cookie. Here is an example:

Another note: the code below uses Newtonsoft.Json (the JsonConvert lines). It should come out of the box in an MVC4 project, but for an MVC3 project, you can just add it via nuget.

public class UserCacheModel
{
    public string FullName { get; set; }
    public string Preference1 { get; set; }
    public int Preference2 { get; set; }
    public bool PreferenceN { get; set; }
}

public static class UserCacheExtensions
{
    private const string CookieName = "UserCache";

    // put the info in a cookie
    public static void UserCache(this HttpResponseBase response, UserCacheModel info)
    {
        // serialize model to json
        var json = JsonConvert.SerializeObject(info);

        // create a cookie
        var cookie = new HttpCookie(CookieName, json)
        {
            // I **think** if you omit this property, it will tell the browser
            // to delete the cookie when the user closes the browser window
            Expires = DateTime.UtcNow.AddDays(60),
        };

        // write the cookie
        response.SetCookie(cookie);
    }

    // get the info from cookie
    public static UserCacheModel UserCache(this HttpRequestBase request)
    {
        // default user cache is empty
        var json = "{}";

        // try to get user cache json from cookie
        var cookie = request.Cookies.Get(CookieName);
        if (cookie != null)
            json = cookie.Value ?? json;

        // deserialize & return the user cache info from json
        var userCache = JsonConvert.DeserializeObject<UserCacheModel>(json);
        return userCache;
    }

}

With this, you can read / write the cookie info from a controller like this:

// set the info
public ActionResult MyAction()
{
    var fullName = MethodToGetFullName();
    var userCache = new UserCache { FullName = fullName };
    Response.UserCache(userCache);
    return Redirect... // you must redirect to set the cookie
}

// get the info
public ActionResult MyOtherAction()
{
    var userCache = Request.UserCache();
    ViewBag.FullName = userCache.FullName;
    return View();
}
danludwig
  • 46,965
  • 25
  • 159
  • 237
  • Thanks for your response. Question: how many data can I put in a single cookie? I mean, Do I have to create a comma separated value to store firstname;lastname in my cookie? Last question: what if user leave the website without logging out? Cookie is still present... Thanks anyway. – Bronzato Feb 13 '13 at 11:55
  • I have updated my answer with code that demonstrates how you can store additional values in a cookie using JSON. As for the presence of a cookie when the user leaves the site, you could change the Expires property to tell the browser to delete the cookie when the user closes their browser. Just don't store any sensitive information in the cookie like credit card number or anything like that! – danludwig Feb 13 '13 at 12:04
  • One more question: why do you named it 'usercache...'? Is it cached somewhere when working with cookies? – Bronzato Feb 13 '13 at 13:07
  • You can name the class anything you like. `UserCacheModel` was off the top of my head. In our application, the class is actually called `TenancyModel`, and stores information about the user's system tenancy. Use `UserCookieInfo` if you like that better. – danludwig Feb 13 '13 at 13:46
  • Thank you very much. Your help was precious. – Bronzato Feb 13 '13 at 17:26