Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the logged in username in ASP.NET MVC3 intranet application

I am working on a MVC 3 intranet application ( windows authentication ). The application must display the profile page of the user once a user logs in. In order to do that the username of the logged in user must be passed in as a route parameter in the following route in Global.asax.cs.

routes.MapRoute(
    "Initial",
    "{controller}/{action}/{emailAlias}", // URL with parameters
    new { controller = "Home", action = "Home", userId = **<USERNAME>**}
);

Here, for the I've used some alternatives.

  1. At first I used Environment.Username. Which works well in development. But not after publishing. Because then Environment.Username yields the name of the applications pool which the app runs in. As described here.

  2. Controller.User.Identity.Name is used to get the desired username in controllers, works well in pre and post publishing. But it cannot be used in the context of Global.asax.cs.

  3. System.Web.HttpContext.Current.User.Identity.Name yields null reference.

  4. System.Security.Principal.WindowsIdentity.GetCurrent().Name works kind of same as Environment.Username

I'm sure it's easy to figure out that I'm a noob by now. Maybe I've missed something obvious. If so please point that out or please tell me of a simple solution thanks in advance.

like image 644
phabtar Avatar asked Jul 22 '11 06:07

phabtar


1 Answers

The global.asax code is supposed to be run at application startup (and shutdown) and you don't have any session or a user at that time (hence the name global). Why do you need the username in the route? You should just use User.Identity.Name in the controllers' code to identify the user instead of relying in getting it as a parameter.

like image 112
Mika Tähtinen Avatar answered Oct 24 '22 17:10

Mika Tähtinen