【发布时间】:2014-09-30 22:34:59
【问题描述】:
我有一个 webapi 项目和一个存储库项目。
我已配置为使用 oauth,它使用 owin 中间件承载令牌身份验证。
我有一个包含多个存储库的工作单元。
在存储库中,我想根据登录用户过滤数据。
我希望所有存储库都通过依赖注入获取登录用户。
我可以在 webapi 操作中访问已登录的用户,但我正在努力弄清楚是否/如何使用 DI 注入当前用户;因为授权是通过 webapi Authorize 进行的?:
[Authorize(Roles = "User")]
public IQueryable<Folder> Folders()
{
// return UnitOfWork.FolderRepository.All().OrderBy(o=>o.FolderId).Skip(10).Take(50);
var test = HttpContext.Current.GetOwinContext().Authentication;
//test is populated with the logged on user here, but I don't want to set the user details of the UOW in every action in my controllers
return UnitOfWork.FolderRepository.All();
}
因此,在操作文件夹中,授权注释将用户登录。但是我已经用 DI 在控制器构造函数中实例化了工作单元:
public FolderController(IUnitOfWork uow, UserManager<IdentityUser,int> usermanager)
{
UnitOfWork = uow;
UserManager = usermanager;
}
IOC 容器:
public static IContainer Initialize()
{
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
x.For<HttpContextBase>()
.HybridHttpOrThreadLocalScoped()
.Use(() => new HttpContextWrapper(HttpContext.Current));
x.For<IUnitOfWork>().HttpContextScoped().Use(
() => new UnitOfWork(new BreezeValidator
(new UserManager<AspNet.Identity.SQLServer.IdentityUser, int>(new UserStore(new SqlDatabase()))))
);
}
}
我曾尝试传入 HttpContext.Current.GetOwinContext(),但此时尚未进行授权,因此尚未设置 Principal。
我查看了 actionfilters(在授权过滤器之后运行),但不知道如何将带有已登录用户集的新工作单元实例返回给控制器。
...或者我是否可以通过操作过滤器在控制器上设置属性?
所以问题真的是,如何在我的所有控制器的工作单元中设置用户详细信息,而不需要大量重复?
谢谢
编辑:我有一个可行的解决方案,但仍不确定这是正确的方法:
我创建了一个动作过滤器,然后从那里获取控制器并在控制器的 unitOfWork 属性上设置一个 UserPrincipal 属性。
using Project1.Web.Controllers;
using System;
using System.Linq;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace Project1.Web.Filters
{
public class InjectUserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var action = actionContext.ControllerContext.Controller;
UowApiController ctrl = (UowApiController)actionContext.ControllerContext.Controller;
ctrl.UnitOfWork.UserPrincipal = actionContext.RequestContext.Principal;
}
}
然后,在我的 UserPrincipal 的 UnitOfWork 设置器中,我在包含的存储库中设置了 UserPrincipal:
public IPrincipal UserPrincipal
{
get
{
return this.userPrincipal;
}
set
{
this.userPrincipal = value;
((Repository<Folder>)FolderRepository).UserPrincipal = value;
}
}
现在可以了,但是没有实现依赖注入。
另外我想知道这是否是一种“正确”的方法,或者什么是更好的方法?
【问题讨论】:
标签: asp.net-web-api dependency-injection controller authorization