ASP.NET控制器基类User.Identity.Name

正如本文所述,我创建了一个抽象的基本控制器类,以便能够将数据从控制器传递到master.page。 在这种情况下,我想在我的数据库中查找用户,查询User.Identity.Name(仅当他登录时)。

但是,我注意到在这个抽象基类中, User属性始终为null 。 要做到这一点,我该怎么办?

非常感谢

正如Paco建议的那样,viewdata直到你尝试使用它之后才会被初始化。

尝试重写Controller.Initialize():

 public abstract class ApplicationController : Controller { private IUserRepository _repUser; public ApplicationController() { } protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); _repUser = RepositoryFactory.getUserRepository(); var loggedInUser = _repUser.FindById(User.Identity.Name); ViewData["LoggedInUser"] = loggedInUser; } } 

要使用该用户,您应该从中获取当前页面

 HttpContext.Current.User.Identity.Name 

通过在web.config中将身份validation设置为Windows,您可以使用User.Identity.Name获取用户

我在静态Utlilites类上使用Page类。 像那样;

Page P =(页)HttpContext.Current.Handler;

我可以通过P对象获取当前请求页面的所有属性。

你试过这个:ControllerContext.HttpContext.Current.User.Identity.Name?