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

懵懂的女人 提交于 2019-12-01 14:38:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6786380/getting-the-logged-in-username-in-asp-net-mvc3-intranet-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!