![](/img/trans.png)
[英]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.