如何将存储库传递给 ASP.NET MVC 中的授权属性

2024-02-13

我是温莎城堡,它非常适合控制器构造函数传递正在使用的存储库。

private IStoryRepository Repository;
public StoryController(IStoryRepository Repository)
{
    this.Repository = Repository;                   
}

现在我在管理区域中有一个操作来显示主管理菜单。我使用了自定义授权属性,它只会检查登录用户是否是管理员(只是用户表中的 isAdmin 标志)

 [AdminAuthorize]
 public ActionResult Menu()

 private IStoryRepository Repository;
 /// <summary>
 /// Initializes a new instance of the <see cref="AdminAuthorizeAttribute"/> class.
 /// </summary>
 public AdminAuthorizeAttribute(IStoryRepository Repository)
 {
     this.Repository = Repository;
 }

 /// <summary>
 /// Checks if the user is authorised
 /// </summary>
 /// <param name="httpContext">The HTTP context.</param>
 /// <returns>
 ///    <c>true</c> if authorized; otherwise, <c>false</c>.
 /// </returns>
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {
    return this.Repository.UserIsAdmin(httpContext.User.Identity.Name);
 }

如何让 Castle 将存储库传递到属性构造函数中,就像控制器构造函数一样?


你基本上有两个选择。将过滤器包装在代理中,可以找到一个很好的例子here http://iridescence.no/post/Constructor-Injection-for-ASPNET-MVC-Action-Filters.aspx.

或者,在自定义过滤器中,您可以执行显式容器调用。例如使用 StructureMap (我没有广泛使用城堡)

ObjectFactory.GetInstance(IStoryRepository)

可能还有第三种方法,即扩展 ActionInvoker 来进行注入,但我不确定这是如何完成的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将存储库传递给 ASP.NET MVC 中的授权属性 的相关文章

随机推荐