mvc custom filter that contains 2 filters

时间:2017-07-12 08:01:46

标签: asp.net asp.net-mvc asp.net-mvc-5

I need to create a custom action filter attribute, that contains in it a declaration of 2 other filters.

For example:

[ContainsTwoFilters]
public ActionResult Index()
{
    return View();
}

Instead of:

[Filter1]
[Filter2]
public ActionResult Index()
{
    return View();
}

Desperate for your help. Thanks.

1 个答案:

答案 0 :(得分:1)

You can't just inherit your filter in your ContainsTwoFilters becouse FilterAttribute is class and there is no multiple class inheritance in C#.

What you can do is to call all methods of Filter1 and Filter1 that you need inside your ContainsTwoFilters.

Something like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class ContainsTwoFilters : ActionFilterAttribute
{
    private Filter1Attribute filter1;
    private Filter2Attribute filter2;
    public ContainsTwoFilters()
    {
        //Init filters
        filter1 = new Filter1Attribute();
        filter2 = new Filter2Attribute();
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        //Here we can call 2 filters
        filter1.OnAuthorization(filterContext);
        filter2.OnAuthorization(filterContext);
    }

    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        //And here only one
        filter2.OnActionExecuting(actionContext);
    }
}

Note that if you annotate your method like this:

[ContainsTwoFilters]
[Filter2]
public ActionResult Index()
{
    return View();
}

Your Filter2 methods will be called twice. Be carefull.