ActionFilterAttribute - 适用于特定控制器类型的操作

时间:2009-09-17 17:06:39

标签: c# asp.net-mvc model-view-controller

我正在使用ActionFilterAttribute来执行自定义身份验证逻辑。该属性仅用于包含我的身份验证逻辑的派生Controller类。

这是我的控制器,源自我的自定义控制器类,以及一个示例属性:

public class MyController : CustomControllerBase
{

   [CustomAuthorize(UserType = UserTypes.Admin)]
   public ActionResult DoSomethingSecure()
   {
      return View();
   }

}

以下是我的ActionFilterAttribute示例:

public class CustomAuthorizeAttribute : ActionFilterAttribute
{
   public MyUserTypes UserType { get; set; }

   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
      myUser user = ((CustomControllerBase)filterContext.Controller).User;

      if(!user.isAuthenticated)
      {
         filterContext.RequestContext.HttpContext.Response.StatusCode = 401;
      }
   }
}

效果很好。

以下是问题:我是否可以要求此属性仅用于我的自定义控制器类型中的操作?

2 个答案:

答案 0 :(得分:16)

您可以将ActionFilter放在类本身上。该类中的所有操作都将实现ActionFilter。

[CustomAuthorize]
public class AuthorizedControllerBase : CustomControllerBase
{
}

public class OpenAccessControllerBase : CustomControllerBase
{
}

public class MyRealController : AuthorizedControllerBase 
{
    // GET: /myrealcontroller/index
    public ActionResult Index()
    {
        return View();
    }
}

答案 1 :(得分:7)

基于我的系统的评论和限制,我采用了混合方法。基本上,如果请求是通过缓存路由发出的,或者由于任何原因未设置“用户”,则身份验证会以正确的方式失败。

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
  private MyUser User { get; set; }

  public override void OnAuthorization(AuthorizationContext filterContext)
  {
    //Lazy loads the user in the controller.
    User = ((MyControllerBase)filterContext.Controller).User;

    base.OnAuthorization(filterContext);
  }

  protected override bool AuthorizeCore(HttpContextBase httpContext)
  {
    bool isAuthorized = false;
    string retLink = httpContext.Request.Url.AbsolutePath;

    if(User != null)
    {
      isAuthorized = User.IsValidated;
    }

    if (!isAuthorized)
    {
      //If the current request is coming in via an AJAX call,
      //simply return a basic 401 status code, otherwise, 
      //redirect to the login page.
      if (httpContext.Request.IsAjaxRequest())
      {
        httpContext.Response.StatusCode = 401;
      }
      else
      {
        httpContext.Response.Redirect("/login?retlink=" + retLink);
      }
    }

    return isAuthorized;
  }
}