Search code examples
c#asp.net-mvcasp.net-mvc-4simplemembership

How to create custom BaseController to keep data about user while user is logged in


I use SimpleMembership in my app and when I need to get the current user's userId I use WebSecurity.CurrentUserId but this invokes the database and I need to reduce this call to the database.

That is why I want to create BaseController : Controller to store userId here. What is the best way to implement this?

I can create:

public class BaseController : Controller
{
     public int CurrentUserId { get; set; }
     ...

And after login set this value. But I am sure that this should not be so simple.


Solution

  • Set the User property on your HttpContext to your logged in user. Like this (pulled from my CustomPrincipal implementation)...

    In your Global.asax:

    protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        /// Code to get user
        ...
        ContextHelper.GetHttpContextBase().User = user;
    }
    

    In another helper class:

    public static class ContextHelper
    {
        public static HttpContextBase GetHttpContextBase()
        {
            return new HttpContextWrapper(HttpContext.Current);
        }
    }
    

    Then in your BaseController:

    public abstract class BaseController : Controller
    {
        public new HttpContextBase HttpContext { get; private set; }
    
        protected virtual new ICustomPrincipal User
        {
            get { return HttpContext.User as ICustomPrincipal; }
        }
    }