gpt4 book ai didi

asp.net-mvc - 为依赖注入(inject)设置过滤器属性以接受构造函数中的参数

转载 作者:行者123 更新时间:2023-12-04 10:05:33 25 4
gpt4 key购买 nike

我正在关注此 page 上的 ninject 过滤器属性设置。 .

对他们来说,他们有:

.WithConstructorArgumentFromControllerAttribute<LogAttribute>(
"logLevel", attribute => attribute.LogLevel);

第二个参数是 Func<LogAttribute, object> callback .他们的实际参数列表设置如下:
Log(LogLevel = Level.Debug)

但我的过滤器属性设置如下:
public class AuthAttribute : FilterAttribute { }

public class AuthFilter : IAuthorizationFilter
{

private readonly IUserService userService;
private string[] roles;

//Stuck on the constructor also. How do I accept params?
public AuthFilter(IUserService userService, params string[] roles)
{
this.userService = userService;
this.roles = roles;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
throw new NotImplementedException();
}
}

不知何故,这是错误的。因为我希望我的过滤器看起来像:
[Auth("Admin", "Contrib")]

我的绑定(bind):
 kernel.BindFilter<AuthFilter>(FilterScope.Controller, 0)
.WhenControllerHas<AuthAttribute>()
.WithConstructorArgumentFromControllerAttribute<AuthAttribute>("roles", /*Stuck here*/)

最佳答案

您需要将角色变成属性中的属性。

属性:

public class AuthAttribute : FilterAttribute 
{
public string[] Roles { get; set; }

public AuthAttribute(params string[] roles)
{
this.Roles = roles;
}
}

筛选:
public class AuthFilter : IAuthorizationFilter
{

private readonly IUserService userService;
private readonly string[] roles;

public AuthFilter(IUserService userService, string[] roles)
{
this.userService = userService;
this.roles = roles;
}

public void OnAuthorization(AuthorizationContext filterContext)
{
//do stuff
}
}

Controller
   [AuthAttribute("a", "b")]
public class YourController : Controller
{

}

捆绑:
kernel.BindFilter<AuthFilter>(FilterScope.Controller, 0)
.WhenControllerHas<AuthAttribute>()
.WithConstructorArgumentFromControllerAttribute<AuthAttribute>("roles", attribute => attribute.Roles);

关于asp.net-mvc - 为依赖注入(inject)设置过滤器属性以接受构造函数中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6205187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com