2009-01-08 93 views
4

this post所述,我創建了一個抽象基類控制器類,以便能夠將數據從控制器傳遞到master.page。在這種情況下,我想在我的數據庫中查找用戶,查詢User.Identity.Name(僅當他登錄時)。ASP.NET控制器基類User.Identity.Name

但是,我注意到在這個抽象基類中User屬性總是null。我需要做些什麼才能做到這一點?

非常感謝

+0

什麼樣的用戶?域用戶?表單認證?您如何在您的網站web.config中配置身份驗證?更詳細的信息會對你獲得一個很好的答案非常有幫助。 – 2009-01-08 21:50:44

+0

你是對的克雷格 - 我已經添加了另一個答案,它提供了我的問題的更多細節。感謝您的麻煩。 – Masterfu 2009-01-09 19:11:52

回答

3

要使用的用戶,您應該從

HttpContext.Current.User.Identity.Name 
0

我使用Page類我靜Utlilites類獲取當前頁面。像那樣;

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

,我可以得到通過P對象的所有屬性的當前請求的頁面..

0

您是否嘗試過這樣的: ControllerContext.HttpContext.Current.User.Identity.Name?

1

通過在web.config中設置身份驗證到Windows,就可以得到用戶與User.Identity.Name

7

由於帕科建議的,可視數據沒有初始化,直到您嘗試使用它後。

嘗試重寫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; 
    } 
}