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.
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.
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.
System.Web.HttpContext.Current.User.Identity.Name
yields null reference.
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.
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.