c# – ASP.NET MVC3 ActionFilterAttribute注入?

前端之家收集整理的这篇文章主要介绍了c# – ASP.NET MVC3 ActionFilterAttribute注入?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嘿,我已经成功地可以在我的FilterAttribute中使用属性注入,但是我想知道是否可能将它移动到构造函数中?

我当前的代码

  1. // AuthAttribute.cs
  2.  
  3. public class AuthAttribute : ActionFilterAttribute
  4. {
  5. public Roles _authRoles { get; private set; }
  6.  
  7. [Inject]
  8. private readonly IAuthorizationService _service;
  9.  
  10. public AuthAttribute(Roles roles)
  11. {
  12. _authRoles = roles;
  13. }
  14.  
  15. public override void OnActionExecuting(ActionExecutingContext filterContext)
  16. {
  17. if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
  18. {
  19. string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
  20. string redirectUrl = string.Format("?returnUrl={0}",redirectOnSuccess);
  21. string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
  22.  
  23. filterContext.HttpContext.Response.Redirect(loginUrl,true);
  24. }
  25. else
  26. {
  27. bool isAuthorized = _service.Authorize(GetUserSession.Id,_authRoles.ToString());
  28.  
  29. if (!isAuthorized)
  30. {
  31. // TODO: Make custom "Not Authorized" error page.
  32. throw new UnauthorizedAccessException("No access");
  33. }
  34. }
  35. }
  36. }
  1. // TestController.cs
  2.  
  3. [Auth(Roles.Developer)]
  4. public ActionResult Index()
  5. {
  6. // Some smart logic
  7. }

提前致谢!

解决方法

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

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

  1. public class AuthAttribute : ActionFilterAttribute
  2. {
  3. public Roles _authRoles { get; private set; }
  4.  
  5. [Inject]
  6. private readonly IAuthorizationService _service;
  7.  
  8. public AuthAttribute(Roles roles)
  9. {
  10. _authRoles = roles;
  11. }
  12.  
  13. public AuthAttribute(Roles roles,IAuthorizationService authSvc)
  14. : this(roles)
  15. {
  16. this.service = authSvc;
  17. }
  18.  
  19. // ...
  20. }

猜你在找的C#相关文章