0

我目前在 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 方法中存在的代码(如上所示)。我不知道该怎么办?对此的任何帮助都是值得赞赏的;

4

2 回答 2

4

看起来 Email 属性为空,因此您不能对其调用.ToString方法。顺便说一句,该MembershipUser.Email属性已经是一个字符串,因此.ToString()在其上调用 a 几乎没有任何意义。

此外,我建议您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变量而没有用它做很多有用的事情。你确定真的有必要吗?

于 2012-09-20T09:48:44.063 回答
2

可能Membership.GetUser()已返回 null - 客户端是否经过身份验证?

也许您需要[Authorize]在控制器上放置一个属性。

调试器是你的朋友!

于 2012-09-20T09:44:38.390 回答