0

작성 조치에서 사용자 ID가 필요한 컨트롤러가 있습니다.새 오브젝트를 생성 할 때 데이터베이스에 사용자 ID 저장

다음은 컨트롤러입니다.

public ActionResult Create(MyCreateViewModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      var myobject = new MyObject 
      { 
       Attrib1 = DateTime.Now.Date, 
       Attrib2 = model.Etichetta, 
       UserId = // I need the user ID... 
      }; 

      // Save the object on database...     

      return RedirectToAction("Index"); 
     } 
     return View(model); 
    } 

나는 응용 프로그램에 걸쳐 userID을 관리 할 수있는 MVC 4의 가장 좋습니다

MVC 4의 SimpleMembership와 함께 제공되는 UserProfile 테이블을 사용하고 있습니다?

모든 Entity 클래스에 User 속성을 포함해야합니까?

Session[] 변수를 사용해야합니까?

+0

이 사용자 ID는 현재 로그인 한 사용자의 ID입니까? – Andrei

+0

예, 현재 로그인 한 사용자에 대한 참조가 필요합니다. –

답변

2

UserProfiles 테이블에서이 줄을 사용하여 userId을 얻을 수 있습니다.

var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name); 

또한이 기능을 사용하여 사용자가 채울 수있는 사용자 정의 열을 포함하여 전체 프로필을 가져올 수 있습니다.

public static UserProfile GetUserProfile() 
     { 
      using (var db = new UsersContext()) 
      { 
       var userId = WebSecurity.GetUserId 
          (HttpContext.Current.User.Identity.Name); 
       var user = db.UserProfiles 
          .FirstOrDefault(u => u.UserId == userId); 
       if (user == null) 
       { 
        //couldn't find the profile for some reason 
        return null; 
       } 
       return user; 
      } 
     } 
+0

이게 맞다고 생각합니다. – Andrei

+0

'WebSecurity.GetUserId (HttpContext.Current.User.Identity.Name)'가 작동합니다. 함수를 사용하고 싶다면 어디에 넣어야합니까? UserProfile 모델 클래스 안에 있지 않거나 테이블의 새로운 속성으로 변환 될 것입니다 ... 맞습니까? –

+0

은 SimpleMembership 또는 WebMatrix에서 OOTB 함수입니다. 클래스 파일 ('UserHelpers'라고 함)에 쉽게 액세스 할 수 있도록이 두 조각이 있습니다. – Eonasdan