首页 > 解决方案 > 当列表确实包含对象时,IEnumerable 上的对象 Null 错误

问题描述

我正在建立一个基本上是博客主机的网站。用户可以编写故事,其他用户可以阅读和评论它们。用户可以阅读任何故事(当前),无论他们是否已登录,但只有在他们有帐户并已登录时才能评论故事。

当我登录时,这有效。我将与故事相关的评论传递给视图模型,并通过模型中的评论运行 foreach 循环以将它们打印出来。我有一个属性IsAnonymous来检查这个人是否登录,然后我有另一个属性,IsAuthorOfComment如果登录的人也写了评论,我可以打印编辑/删除评论功能。

如果您已登录,这将正常工作。如果您没有登录,我会Object reference not set to an instance of an object.在调试器中看到两个有效的注释正在传递给视图,但我在其中找不到任何null导致此问题的属性错误。

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

我的控制器动作

[HttpGet]
[AllowAnonymous]
public ActionResult Details(int id)
    {
    bool isAnonymous;

    var FoundStory = _dbContext.Stories.SingleOrDefault(x => x.Id == id);

    if (FoundStory == null)
    {
        return HttpNotFound();
    }

    //get the logged in userId
    string signedInUserId = User.Identity.GetUserId();

    //if the person reading the article isn't signed in, the userId will come back null
    //need to guard against this in view so the view doesn't break
    //this is here because in the view, we want to display a comment box if the user is signed in, and
    //if they're not signed in, redirect them to the log-in page
    //check to see if the user is reading the article anonymously
    //if the user is anonymous, set isAnonymous to true and do not pass the user to the IsCommenter function call
    //if the user is not anonymous, set isAnonymous to false and pass the user to the IsCommenter function
    if (signedInUserId == null)
    {
        isAnonymous = true;

    } else
    {
        isAnonymous = false;
    }

    var SignedInUser = _dbContext.Users.SingleOrDefault(x => x.Id == signedInUserId);

    var comments = _dbContext
        .Comments
        .Where(x => x.StoryId == FoundStory.Id)
        .OrderByDescending(x => x.LastUpdated)
        .ToList();

//helper.IsCommenter compares a comments authorid to the signed in user's id, we need to
//must ensure the user is not anonymous and that the comments returned are equal or greater than one otherwise helper.IsCommenter may throw an exception
    if (!isAnonymous && comments.Count() >= 1)
    {
        helper.IsAuthorOfComment(comments, SignedInUser);
    }

    var viewModel = new StoryDetailsViewModel
    {
        IsAnonymous = isAnonymous,
        StoryId = FoundStory.Id,
        AuthorId = FoundStory.AuthorId,
        Story = FoundStory,
        User = SignedInUser,
        Comments = comments
    };

    return View(viewModel);
}

标签: c#asp.netasp.net-mvc

解决方案


推荐阅读