c# - 当列表确实包含对象时,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);
}
解决方案
推荐阅读
- jquery - 从多个元素的属性构建数组
- java - 带有嵌入式 postgres 的 Spring Boot 2 - 必须存在至少一个 JPA 元模型
- java - 将 double 转换为 int 返回 0 而不是 1 为什么?
- android - 在同一 TableRow 中查找元素
- c# - 如何从同一个 xpath 表达式中的两个表中获取行?
- postgresql - 如何提高 JPA/PostgreSQL 查询性能?
- ajax - 使用代理,使用 withCredentials 设置为 true 的 Angular 4 应用程序中未发送 Cookie
- postgresql - pgpool 连接到 postgresql 状态:“节点正在运行。有连接。postgres:关闭”
- python - 如何将依赖链接添加到 setup.py 中的 repo 子目录
- javascript - 如何在html中的按钮悬停上显示?