C# · 12月 27, 2021

c# – ASP.NET MVC3 ActionFilterAttribute注入?

嘿,我已经成功地可以在我的FilterAttribute中使用属性注入,但是我想知道是否可能将它移动到构造函数中?

我当前的代码:

// AuthAttribute.cspublic class AuthAttribute : ActionFilterAttribute{ public Roles _authRoles { get; private set; } [Inject] private readonly IAuthorizationService _service; public AuthAttribute(Roles roles) { _authRoles = roles; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath; string redirectUrl = string.Format(“?returnUrl={0}”,redirectOnSuccess); string loginUrl = FormsAuthentication.LoginUrl + redirectUrl; filterContext.HttpContext.Response.Redirect(loginUrl,true); } else { bool isAuthorized = _service.Authorize(GetUserSession.Id,_authRoles.ToString()); if (!isAuthorized) { // TODO: Make custom “Not Authorized” error page. throw new UnauthorizedAccessException(“No access”); } } }} // TestController.cs[Auth(Roles.Developer)]public ActionResult Index(){ // Some smart logic}

提前致谢!

解决方法 不,这不可能作为构建器 must be simple types的参数.

为了测试的目的,您可以使用另一个构造函数(因为您不应该在测试中使用IoC容器):

public class AuthAttribute : ActionFilterAttribute{ public Roles _authRoles { get; private set; } [Inject] private readonly IAuthorizationService _service; public AuthAttribute(Roles roles) { _authRoles = roles; } public AuthAttribute(Roles roles,IAuthorizationService authSvc) : this(roles) { this.service = authSvc; } // …}