I'm working on an application which has two projects:
- Core - houses the data access layer using repository pattern and domain-driven design
UI - using ASP.Net MVC. Currently, I am able to get the current logged in user's info(id, name, etc..) inside the UI controller via the User property like this:
using Microsoft.AspNet.Identity; public class ExamController : Controller { IExaminationRepository _repository; public ExamController() { _repository = RepositoryFactory.Get<IExaminationRepository>(); } [HttpPost] [Authorize(Roles = "Examiner")] public ActionResult Create(ExamViewModel viewModel) { try { ExaminationDomain domain = Mapper.Map<ExamViewModel, ExaminationDomain>(viewModel); //TODO: Move this to the repository domain.AuthorId = User.Identity.GetUserId(); _repository.Add(domain); return RedirectToAction("Index"); } catch { return View(); } } }
I would like to move the line: domain.AuthorId = User.Identity.GetUserId();
to my repository concrete implementation like this:
using Microsoft.AspNet.Identity;
using System.Security.Principal;
internal class ExaminationRepository
{
public DBEntities context;
public IPrincipal User;
public ExaminationRepository(DBEntities context)
{
this.context = context;
//I'd like to instantiate User property here:
this.User = "not sure what to instantiate with";
}
public void Add(ExaminationDomain domain)
{
Examination newExam = Mapper.Map<ExaminationDomain, Examination>(domain);
newExam.AuthorId = User.Identity.GetUserId();
newExam.CreatedBy = User.Identity.Name;
newExam.CreatedDate = DateTime.Now;
context.Examinations.Add(newExam);
context.SaveChanges();
}
But I am not sure what to instantiate the User property to in the constructor. I've read some suggestions to use WindowsIdentity.GetCurrent().User
instead of creating a user property but this doesn't contain the user id, only user name.
Any other suggestions on getting user info?
I'd really appreciate some help on this..
Thanks,