2016-09-29 52 views
0

我有這樣的代碼User.Identity.Name扔對象引用未設置爲一個實例

public UserProfile spUserProfileGet() 
     { 
      // this line throw : Object reference not set to an instance 
      var user = HttpContext.Current.User.Identity.Name; 

      //... 

     } 

在我的IIS設置發展,我有

Anonymous Authentication : Disabled 
Windows Authentication : Enabled 

,我越來越

Object reference not set to an instance 

這是爲什麼?我在很多項目中使用這個類之前沒有問題:/

HttpContext.Current.UserNULL,但是爲什麼?

+1

可能重複[什麼是NullReferenceException,以及如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-doi-i-fix -it) – DavidG

+0

是的,User對象是NULL,但是爲什麼? – Muflix

+0

閱讀重複的問題,它告訴你如何確定。 – DavidG

回答

0

問題是,我從global.asax Application_BeginRequest()中調用HttpContext.Current.User,它尚未包含此對象。以下是應用程序生命週期https://msdn.microsoft.com/en-us/library/ms178473.aspx的描述,當我將代碼複製到 Application_PostAuthenticateRequest時,它現在可以工作。

問題仍然存在,是Application_PostAuthenticateRequest被觸發兩次。