Background: I'm building more and more web applications where the designers / template makers decide that adding a "profile picture" and some other user-related data, of course only when someone is logged in.
As most ASP.NET MVC developers I use viewmodels to provide razor layouts with the information that I need shown, sourced from repositories et al.
It is easy to show a user name through using
HttpContext.Current.User.Identity.Name
What if I want to show information that's saved in my backing datastore on these pages? Custom fields in the ApplicationUser class like a business unit name or a profile picture CDN url.
(for sake of simplicity let's assume I use the Identity Framework with a Entity Framework (SQL database) containing my ApplicationUsers)
Question
How do you solve this:
- Without poluting the viewmodel/controller tree (e.g. building a BaseViewModel or BaseController populating / providing this information?
- Without having to roundtrip the database every page request for these details?
- Without querying the database if a user is not logged in?
- When you cannot use SESSION data (as my applications are often scaled on multiple Azure instances - read why this isn't possible here- I'm not interested in SQL caching or Redis caching.
I've thought about using partials that new their own viewmodel - but that would still roundtrip the SQL database every pageload. Session data would be safe for now, but when scaled up in azure this isn't a way either. Any idea what would be my best bet?
TLDR;
I want to show user profile information (ApplicationUser) on every page of my application if users are logged in (anon access = allowed). How do I show this info without querying the database every page request? How do I do this without the Session class? How do I do this without building base classes?
FormsAuthenticationTicketwhen the user logs in, so they can be read from the cookie in every request rather than calling the database (although adding a image to the cookie may not be appropriate). I don't use Identity but I believe it allow you to do this using Claims._Layout. In the_Layoutdefine aDivwhich should contain your views, and use Ajax to load thePartialViewcontent. This way you only load the profile details once