[英]ASP.NET Controller Base Class User.Identity.Name
As described in this post , I created an abstract base controller class in order to be able to pass data from a controller to master.page. 如在描述的这篇文章中,我创建一个抽象基类控制器,以便能够从控制器的数据传递到master.page。 In this case, I want to lookup a user in my db, querying for User.Identity.Name (only if he is logged in).
在这种情况下,我想在我的数据库中查找用户,查询User.Identity.Name(仅当他登录时)。
However, I noticed that in this abstract base class the User
property is always null
. 但是,我注意到在这个抽象基类中,
User
属性始终为null
。 What do I have to do to get this working? 要做到这一点,我该怎么办?
Thanks a lot 非常感谢
As Paco suggested, the viewdata isn't initialized till after you are trying to use it. 正如Paco建议的那样,在您尝试使用它之前,viewdata尚未初始化。
Try overriding Controller.Initialize() instead: 尝试重写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中将身份验证设置为Windows,您可以使用User.Identity.Name获取用户
I use Page class on my static Utlilites classes. 我在静态Utlilites类上使用Page类。 Like that;
像那样;
Page P = (Page)HttpContext.Current.Handler; Page P =(页)HttpContext.Current.Handler;
and i can get all properties via the P object for the current requested page.. 我可以通过P对象获取当前请求页面的所有属性。
你试过这个:ControllerContext.HttpContext.Current.User.Identity.Name?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.