[英]Test an Asp.Net Controller action method which uses User.Identity.Name?
[英]ASP.NET Controller Base Class 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中将身份验证设置为Windows,您可以使用User.Identity.Name获取用户
我在静态Utlilites类上使用Page类。 像那样;
Page P =(页)HttpContext.Current.Handler;
我可以通过P对象获取当前请求页面的所有属性。
你试过这个:ControllerContext.HttpContext.Current.User.Identity.Name?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.