C# ASP.NET 控制器基类 User.Identity.Name
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/426110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET Controller Base Class User.Identity.Name
提问by Masterfu
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. In this case, I want to lookup a user in my db, querying for User.Identity.Name (only if he is logged in).
如在描述的这篇文章中,我创建一个抽象基类控制器,以便能够从控制器的数据传递到master.page。在这种情况下,我想在我的数据库中查找用户,查询 User.Identity.Name(仅当他登录时)。
However, I noticed that in this abstract base class the User
property is always null
. What do I have to do to get this working?
但是,我注意到在这个抽象基类中,User
属性总是null
. 我该怎么做才能让它发挥作用?
Thanks a lot
非常感谢
回答by Adam Right
To use the user, you should get the current page from
要使用用户,您应该从
HttpContext.Current.User.Identity.Name
回答by Adam Right
I use Page class on my static Utlilites classes. Like that;
我在静态 Utlilites 类上使用 Page 类。像那样;
Page P = (Page)HttpContext.Current.Handler;
页面 P = (Page)HttpContext.Current.Handler;
and i can get all properties via the P object for the current requested page..
我可以通过 P 对象获取当前请求页面的所有属性。
回答by Adam Right
Have you tried this: ControllerContext.HttpContext.Current.User.Identity.Name?
你有没有试过这个:ControllerContext.HttpContext.Current.User.Identity.Name?
回答by Danny
By setting authentication to Windows in web.config, you can get the user with User.Identity.Name
通过在 web.config 中设置对 Windows 的身份验证,您可以获得 User.Identity.Name 的用户
回答by Melethril
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;
}
}