c# – ASP.NET MVC3 ActionFilterAttribute注入?
发布时间:2020-12-15 03:58:31 所属栏目:百科 来源:网络整理
导读:嘿,我已经成功地可以在我的FilterAttribute中使用属性注入,但是我想知道是否可能将它移动到构造函数中? 我当前的代码: // AuthAttribute.cspublic class AuthAttribute : ActionFilterAttribute{ public Roles _authRoles { get; private set; } [Inject]
嘿,我已经成功地可以在我的FilterAttribute中使用属性注入,但是我想知道是否可能将它移动到构造函数中?
我当前的代码: // AuthAttribute.cs public 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; } // ... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |