Where can I store email and userId in my ASP.NET MVC application so I don't have to retrieve it

I'm writing an ASP.NET MVC application and I'm using forms authentication with the default IPrincipal, IIDentity, etc.

In my authentication ticket I'm storing the username in the name parameter.

However, I'm running into instances where on every request my master layout needs access to not only the username, but also the email and userid of the user.

I need the email so I can load a gravitar icon for the user, the username so I can have a friendly display name in the top bar, and the userid so I can define certain links specific to that userid (ie, /users/edit/2332).

What is the cleanest way to store not just the username but also the userid and email?

Custom Principal/Identity objects? Cache? Session? Some other way?


Use a custom IPrincipal object with your own cookie management.

I would suggest serializing the custom IPrinicipal object to JSON and setting your cookie.UserData to the serialized string. That was it's easy to deserialize when the cookie comes back in.

<strong>EDIT: Example of a custom IPrincipal object and authentication cookie management</strong>

The IPrincipal object (note I'm using Json.NET for serialization)

public class SimplePrincipal : IPrincipal { private IIdentity _identity; [JsonIgnore] public IIdentity Identity { get { return _identity ?? (_identity = new GenericIdentity(Name)); } } public string Name { get; set; } public int WebUserId { get; set; } public string Email { get; set; } public long FacebookUserId { get; set; } public IEnumerable<string> Roles { get; set; } public bool IsInRole(string role) { return Roles.Contains(role); } /// <summary> /// Get's a JSON serialized string of a SimplePrincipal object /// </summary> public static string GetCookieUserData(SimplePrincipal principal) { return JsonConvert.SerializeObject(principal); } /// <summary> /// Creates a SimplePrincipal object using a JSON string from the asp.net auth cookie /// </summary> public static SimplePrincipal CreatePrincipalFromCookieData(string userData) { return JsonConvert.DeserializeObject<SimplePrincipal>(userData); } }

Login Method

private void LoginUser(SimplePrincipal principal, bool isPersistent) { var userData = SimplePrincipal.GetCookieUserData(principal); var authCookie = FormsAuthService.GetAuthCookie(principal.Name, userData, isPersistent); Response.Cookies.Add(authCookie); }

Authentication Module

public class AuthModule : IHttpModule { public void Init(HttpApplication context) { context.AuthenticateRequest += Application_AuthenticateRequest; } private void Application_AuthenticateRequest(Object source, EventArgs e) { var application = (HttpApplication)source; var context = application.Context; // Get the authentication cookie string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = context.Request.Cookies[cookieName]; if (authCookie == null) return; var authTicket = FormsAuthentication.Decrypt(authCookie.Value); context.User = SimplePrincipal.CreatePrincipalFromCookieData(authTicket.UserData); } public void Dispose() { //Don't do anything } }

After all this is wired up correctly, you can simply get the object something like:

var principal = HttpContext.Current.User as SimplePrincipal


I would suggest using Session object for storing this kind of information.


Use Session if you want to keep it alive for the session (also the most straight forward approach). Use TempData if you want to persist it between single requests (or until it is read out).

You can also use querystring or URL params but in this case, I wouldn't suggest it.

Do not use cache as that is shared across all users of the site.

Ideally though, it should be a Custom Identity object


  • How enable GZIP compression for Spring HttpInvoker requests using Tomcat?
  • Json.net Add property to every class containing of a certain type
  • JTable delete multiple rows with AbstractTableModel
  • Why to use _form.html.erb in rails
  • how to connect multiple devices using AndroidViewClient
  • HttpContext.Current is null when in method called from PageAsyncTask
  • readyRead() signal of QextSerialPort (QIODevice) is not being called fast enough
  • An unhandled exception of type 'System.AccessViolationException' occurred
  • Is there a way to focus on a dynamically created form on Angular 4/Ionic3?
  • OpenMP for dependent variables
  • how to deserialize jqgrid multiple group search criteria in asp .net mvc2
  • Xcode launch app error in Mac 10.9 Mavericks
  • how to pass the result model object out of System.Web.Http.ModelBinding.IModelBinder. BindModel?
  • Array to string conversion error
  • Gson serializing Spring beans
  • Getting a generic method to infer the type parameter from the runtime type
  • XBee Linux Serial Port on Rasberry Pi
  • Arduino making decision according to a packet received from serial port
  • Telegram bot API - Inline bot getting Error 400 while trying to answer inline query
  • Android changing fragment order inside FragmentPagerAdapter
  • Jquery popup on mouse over of calendar control
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • How do I get HTML corresponding to current DOM tree?
  • Xcode 4 NSLog Macro link in Xcode 3
  • Play WS (2.2.1): post/put large request
  • How to create a file in java without a extension
  • Different response to non-authenticated users and AJAX calls
  • Fetching methods from BroadcastReceiver to update UI
  • 'TypeError' while using NSGA2 to solve Multi-objective prob. from pyopt-sparse in OpenMDAO
  • Symfony2: How to get request parameter
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • GridView Sorting works once only
  • AT Commands to Send SMS not working in Windows 8.1
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • WPF Applying a trigger on binding failure
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • Linking SubReports Without LinkChild/LinkMaster
  • apache spark aggregate function using min value
  • Is it possible to post an object from jquery to bottle.py?
  • Sorting a 2D array using the second column C++