c# - Order of execution with multiple filters in web api -
i using latest web api
.
i annotate some controllers 3 different filter attributes.
1 [authorize] 2 [ressourceownerattribute derived authorizationfilterattribute] 3 [invalidmodelstateattribute derived actionfilterattribute]
i can not sure filters run in order declared top down.
how define order of execution in web api 2.1
?
https://aspnetwebstack.codeplex.com/workitem/1065#
do still have fix myself ??
some things note here:
- filters executed in following order action: globally defined filters -> controller-specific filters -> action-specific filters.
- authorization filters -> action filters -> exception filters
now problem seem mention related having multiple filters of same kind (ex: multiple
actionfilterattribute
decorated on controller or action. case not guarantee order based on reflection.). case, there way in web api using custom implementation ofsystem.web.http.filters.ifilterprovider
. have tried following , did testing verify it. seems work fine. can give try , see if works expected.// start clean replacing filter provider global configuration. // these globally added filters need not ordering filters // executed in order added filter collection config.services.replace(typeof(ifilterprovider), new system.web.http.filters.configurationfilterprovider()); // custom action filter provider ordering config.services.add(typeof(ifilterprovider), new orderedfilterprovider());
public class orderedfilterprovider : ifilterprovider { public ienumerable<filterinfo> getfilters(httpconfiguration configuration, httpactiondescriptor actiondescriptor) { // controller-specific ienumerable<filterinfo> controllerspecificfilters = orderfilters(actiondescriptor.controllerdescriptor.getfilters(), filterscope.controller); // action-specific ienumerable<filterinfo> actionspecificfilters = orderfilters(actiondescriptor.getfilters(), filterscope.action); return controllerspecificfilters.concat(actionspecificfilters); } private ienumerable<filterinfo> orderfilters(ienumerable<ifilter> filters, filterscope scope) { return filters.oftype<iorderedfilter>() .orderby(filter => filter.order) .select(instance => new filterinfo(instance, scope)); } }
//note: here creating base attributes need inherit from. public interface iorderedfilter : ifilter { int order { get; set; } } public class actionfilterwithorderattribute : actionfilterattribute, iorderedfilter { public int order { get; set; } } public class authorizationfilterwithorderattribute : authorizationfilterattribute, iorderedfilter { public int order { get; set; } } public class exceptionfilterwithorderattribute : exceptionfilterattribute, iorderedfilter { public int order { get; set; } }
Comments
Post a Comment