سؤال

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??

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

if you want to use a controller level variable that needs the username, you can override OnActionExecuting event where you can access the authenticated user id. You may have to check for null for the user.identity just to be cautious.

    Obj myObj;
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        myObj = new Obj(User.Identity.Name);
        base.OnActionExecuting(filterContext);
    }

whole discussions is about what is really making, sound like a "state" of permissions, in access of methods/functions, indeed sound like a bigger concept what can live in the controller like object, making a class of that type "state concept"... all discussion about if that live in model/view/controller, can be resolve by using ID/Object in the parameters interchange, but because it's access-data need, is not job for the controller, is job for the dbms and structuring data-access for memory struct of data model, job for a class in any form/model/struct of class modelling an "idea/connection/task". All discussion about model/controller is about efficiency, and efficiency is DBMS in all case.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top