ASP.NET Controller Base Class User.Identity.Name
Asked Answered
E

5

4

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

Etui answered 8/1, 2009 at 21:41 Comment(2)
What kind of user? A domain user? Forms authentication? How have you configured authentication in your site web.config? More detail would be very helpful in getting you a good answer.Godber
You're right Craig - I've added another answer which provides more detail to my problem. Thanks for bothering.Etui
G
7

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;
    }
}
Ganja answered 30/10, 2009 at 15:55 Comment(0)
I
3

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

HttpContext.Current.User.Identity.Name
Immuno answered 8/1, 2009 at 22:31 Comment(1)
System.Web.HttpContext.Current.User.Identity.Name works (MVC 4)Maidinwaiting
H
1

By setting authentication to Windows in web.config, you can get the user with User.Identity.Name

Hatching answered 30/4, 2009 at 16:55 Comment(0)
I
0

I use Page class on my static Utlilites classes. Like that;

Page P = (Page)HttpContext.Current.Handler;

and i can get all properties via the P object for the current requested page..

Immuno answered 12/1, 2009 at 15:42 Comment(0)
A
0

Have you tried this: ControllerContext.HttpContext.Current.User.Identity.Name?

Acentric answered 12/1, 2009 at 20:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.