Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Controller Base Class User.Identity.Name

As described in this post, I created an abstract base controller class in order to be able to pass data from a controller to master.page. In this case, I want to lookup a user in my db, querying for User.Identity.Name (only if he is logged in).

However, I noticed that in this abstract base class the User property is always null. What do I have to do to get this working?

Thanks a lot

like image 504
Masterfu Avatar asked Dec 22 '22 13:12

Masterfu


2 Answers

As Paco suggested, the viewdata isn't initialized till after you are trying to use it.

Try overriding Controller.Initialize() instead:

public abstract class ApplicationController : Controller
{
    private IUserRepository _repUser;

    public ApplicationController()
    {
    }

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

        _repUser = RepositoryFactory.getUserRepository();
        var loggedInUser = _repUser.FindById(User.Identity.Name);
        ViewData["LoggedInUser"] = loggedInUser;
    }
}
like image 87
Melethril Avatar answered Dec 25 '22 01:12

Melethril


To use the user, you should get the current page from

HttpContext.Current.User.Identity.Name
like image 21
Adam Right Avatar answered Dec 25 '22 03:12

Adam Right