2014-03-19 23 views
0

我有一個控制器:在AdminController是具有這個聲明的方法:HttpContext.User.Identity.Name返回一個對象引用錯誤

string user = HttpContext.User.Identity.Name.ToUpper(); 

它給了我未設置爲實例的對象引用對象錯誤...

不過,我還有一個控制器(BatchesController),其中我這樣做:

Regex.Match(HttpContext.User.Identity.Name, @"([^\\]+$)").Groups[0].Value 

它工作正常...

我也有使用它的精細另一個控制器:

public class AuthoriseUser : AuthorizeAttribute 
    { 
     protected override bool AuthorizeCore(HttpContextBase httpContext) 
     { 
      string username = httpContext.User.Identity.Name.ToString().ToUpper(); 
      List<string> a = GetAll(); 
      Boolean authorise = false; 

      if (httpContext == null) 
      { 
       throw new ArgumentNullException("httpContext"); 
      } 

      IPrincipal user = httpContext.User; 
      if (!user.Identity.IsAuthenticated) 
      { 
       authorise = true; 
      } 

對不起,這只是一個片段。但它的工作。

爲什麼它在一個地方失敗?請告訴我,如果你需要更多的背景情況。

回答

0

問題是,我是創建一個新對象AdminController:

AdminController ac = new AdminController(); 

相反,我存儲在用戶在一個變量中,並通過它,而不是使用「用戶」變量。