2017-11-05 5 views
-2

현재 사용자 ID를 저장할 때 Create 내 게시물에서이 오류가 발생합니다.System.NullReferenceException : '개체 참조가 개체의 인스턴스로 설정되지 않았습니다. MVC5

지침, 조언, 솔루션에 대한 링크가 큰 help.Thanks

이 될 것입니다 모든

포스트 Class.cs 내가 currentUserId가 null이 아닌지 확인해야로서 컨트롤러

에서

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

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

+0

이렇게하면 로그인 했습니까? –

+0

오류 이미지의 모양과 함께, 그것은 당신이 이미지에 "}"를 닫고 "{"컨트롤러 위의 "postObje.PostMaker.Id = currentUserId"를 가지고 있기 때문에 다른 클래스/컨트롤러/; " –

답변

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)가있는 경우 고객은 역할을보고이 방법에 대한 액세스를 제한하십시오.

+0

예, 로그인되어 있으며 currentUserId에 적절한 값이 있습니다. –

관련 문제