如何在单独的程序集中获取用户ID [英] How to get User ID inside a separate assembly
问题描述
我正在开发一个有两个项目的应用程序:
I'm working on an application which has two projects:
- 核心-使用存储库模式和域驱动设计来容纳数据访问层
-
UI-使用ASP.Net MVC.目前,我可以通过如下所示的User属性获取UI控制器中当前登录的用户的信息(id,名称等):
- 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();
}
}
}
我想将以下行: domain.AuthorId = User.Identity.GetUserId();
移到我的存储库具体实现中,如下所示:
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();
}
但是我不确定要在构造函数中实例化User属性的内容.我已经阅读了一些使用 WindowsIdentity.GetCurrent().User
的建议,而不是创建用户属性,但这不包含用户ID,仅包含用户名.
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?
真的很感谢您的帮助.
谢谢
推荐答案
我将使用自定义管理器将您的存储库从httpcontext解耦.例如,我有一个名为IAUthenticationManager的接口
I would decouple your repository from the httpcontext with a custom manager. For example I have a interface called IAUthenticationManager
public interface IAUthenticationManager
{
string CurrentUserId();
bool HasCurrentUserRole(string roleName),
}
易于测试并且完全解耦.
Easy to test and fully decoupled.
这篇关于如何在单独的程序集中获取用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!