Question

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.

Was it helpful?

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; }
    }
}

OTHER TIPS

I would use claims to store the user ID. This will persist the information in the cookie and eliminates the need to hit the database every time you need to access it. Here is an article on how to use federated authentication to persist custom claim information in the cookie. This article specifically puts the user ID in the claims. SimpleMembership is already storing the roles in claims.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top