簡體   English   中英

Asp.Net MVC4'對象引用未設置為對象的實例'

[英]Asp.Net MVC4 'Object reference not set to an instance of an object'

我目前在asp.net mvc4中工作。 並實現用戶個人資料信息。 我的控制器即HomeController包含;

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方法中存在的代碼(如上所示)。 我不知道該怎么辦? 任何對此的幫助都是可以的;

看起來Email屬性為null,因此無法在其上調用.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變量時卻沒有做很多有用的事情。 您確定這確實有必要嗎?

可能Membership.GetUser()返回null-客戶端已通過身份驗證嗎?

也許您需要在控制器上放置一個[Authorize]屬性。

調試器是您的朋友!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM