System.NullReferenceException:'对象引用未设置为对象的实例。 MVC5

时间:2017-11-05 20:16:19

标签: c# asp.net-mvc nullreferenceexception

当我想存储当前用户ID时,我在帖子Create方法中收到此错误。

任何指导,建议,解决方案的链接都会有很大帮助。谢谢

发布Class.cs

public class Post
{
    public virtual ApplicationUser PostMaker { get; set; }
}

在控制器

我已经检查过currentUserId不是null

public ActionResult Create(Post post, HttpPostedFileBase upload)
{

    string currentUserId = User.Identity.GetUserId();
    Post postObje = new Post();
    postObje = post;
    ApplicationUser postMaker = db.Users.Find(currentUserId);
    if (ModelState.IsValid)
    {
        postObje.PostMaker.Id = currentUserId; //(Error is in this line)
        db.Post.Add(postObje);
        db.SaveChanges();
    }
}

enter image description here

1 个答案:

答案 0 :(得分:0)

 [Authorize]  //add this to the method   
 public ActionResult Create(Post post, HttpPostedFileBase upload)
        {

            string currentUserId = User.Identity.GetUserId();
            Post postObje = new Post();
            [postObje = post;
            ApplicationUser postMaker = db.Users.Find(currentUserId);
            if (ModelState.IsValid)
            {
                postObje.PostMaker.Id = currentUserId; //(Error is in this line)
                db.Post.Add(postObje);
                db.SaveChanges();
            }
    }

[Authorize]将确保用户必须先登录才能运行该方法。但是,如果您有不同的用户,例如admin,则客户会查看角色以限制对此方法的访问