当我想存储当前用户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();
}
}
答案 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,则客户会查看角色以限制对此方法的访问