2012-09-20 44 views
0

我目前正在使用asp.net mvc4。並實施用戶配置文件信息。我的控制器I-e HomeController包含;Asp.Net MVC4'對象引用未設置爲對象的實例'

public ActionResult Resume() 
{ 
    using (ProfileInfo profile = new ProfileInfo()) 
    { 
     return View(profile.ProfileGetInfoForCurrentUser()); 
    } 
} 

profileinfo類包含一個方法至極返回類型 'ResumeViewModel';

public ResumeViewModel ProfileGetInfoForCurrentUser() 
{ 
    ProfileBase profile = ProfileBase.Create(Membership.GetUser().UserName); 
    ResumeViewModel resume = new ResumeViewModel(); 
    resume.Email = Membership.GetUser().Email.ToString(); 
    resume.FullName = Membership.GetUser().UserName; 
    return resume; 

} 

現在我ResumeViewModel看起來是這樣的;

public class ResumeViewModel 
{ 
    public string FullName { get; set; } 
    public string Email { get; set; } 
} 

雖然我的觀點是強烈類型的'@model PortfolioMVC4.Models.ResumeViewModel'。但是,當我運行這個時,我得到以下錯誤;

Object reference not set to an instance of an object. 
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. 
{ 
Line 14:    ProfileBase profile = ProfileBase.Create(Membership.GetUser().UserName); 
Line 15:    ResumeViewModel resume = new ResumeViewModel(); 
Line 16:    resume.Email = Membership.GetUser().Email.ToString(); 
Line 17:    resume.FullName = Membership.GetUser().UserName; 

我收到第15行的錯誤;這基本上是ProfileGetInfoForCurrentUser方法中存在的代碼(如上所示)。 我不知道該怎麼辦? 對此的任何幫助都是可以理解的;

+0

你爲什麼要放置你的視圖模型? – simonlchilds

+0

我應該刪除它嗎? –

+0

行15沒有辦法拋出NullReferenceException。第14行更有可能,也許Membership.GetUser()不返回用戶,因此訪問UserName屬性失敗。 – SpaceBison

回答

4

它看起來像電子郵件屬性爲空,所以你不能調用.ToString方法。順便說一下MembershipUser.Email屬性已經是一個字符串了,所以調用.ToString()就沒什麼意義了。

此外,我建議你調用Membership.GetUser()方法只有一次,結果緩存到本地變量以避免多個請求錘擊數據庫:

public ResumeViewModel ProfileGetInfoForCurrentUser() 
{ 
    var user = Membership.GetUser(); 
    ProfileBase profile = ProfileBase.Create(user.UserName); 
    ResumeViewModel resume = new ResumeViewModel(); 
    resume.Email = user.Email; 
    resume.FullName = user.UserName; 
    return resume; 
} 

順便說一句,你似乎在宣告一些profile變量沒有用它做很多有用的事情。你確定它確實有必要嗎?

+0

我已經登錄 –

+1

但這並不意味着在數據庫中定義了一個Email。所以即使你登錄了'Email'屬性也可以爲null。所以不要在空對象上調用'.ToString()'。 –

+0

是你的權利,但我也叫profile.GetProfileGroup(「AboutMe」)。GetPropertyValue(「網站」)。ToString()這是一個配置文件property.But當我刪除toString(),我越來越cnno't轉換從對象到字符串 –

2

可能Membership.GetUser()已經返回null - 是客戶端認證?

也許您需要在控制器上添加[Authorize]屬性。

調試器是你的朋友!

+0

是的,對嗎?它返回null –

相關問題