Search code examples
asp.net-mvc-3windows-authenticationintranet

Get current logged in user in controller action in MVC 3


I am working on a MVC 3 intranet application ( windows authentication ). I want the username of current logged in user in my controller action. I have tried lot of variation but cannot get the username . I tried using Environment.Username it worked well in debug mode but when deployed it provided the pool name rather than the username.

Controller action.

  public ActionResult Index()
        {
            LoggedUser usr = new LoggedUser();
            var aa = usr.User;
        }

LoggedUser

public class LoggedUser : Controller
    {
        public LoggedUser()
        {

        }
    }

I was following this post but was not able to make it work Getting the logged in username in ASP.NET MVC3 intranet application

Any help??


Solution

  • To retrieve the currently logged in username you could use the User.Identity.Name property inside your action:

    public ActionResult Index()
    {
        string usr = User.Identity.Name;
        ...
    }
    

    The code you have shown in your question is incorrect. You have defined a LoggedUser and are instantiating this controller inside some Index action. You are not supposed to instantiate controllers manually. That's the responsibility of the framework.