Skip to content

Instantly share code, notes, and snippets.

@kiwipiet
Created July 19, 2016 20:25
Show Gist options
  • Save kiwipiet/b8fd36b5da49194d405a7e54fb290130 to your computer and use it in GitHub Desktop.
Save kiwipiet/b8fd36b5da49194d405a7e54fb290130 to your computer and use it in GitHub Desktop.
Applies FilterAttribute T to all MVC controller actions in case action or it's controller do not have FilterAttribute derived from BaseT
/// <summary>
/// Applies FilterAttribute T to all MVC controller actions
/// in case action or it's controller do not have FilterAttribute derived from BaseT
/// </summary>
/// <example>
/// <![CDATA[
/// FilterProviders.Providers.Add(new DefaultFilterProvider<NoAuthorizeAttribute, AuthorizeUserAttribute>());
/// ]]>
/// </example>
/// <typeparam name="T">FilterAttribute to be applied</typeparam>
/// <typeparam name="TBaseT">FilterAttribute to be checked</typeparam>
public class DefaultFilterProvider<T, TBaseT> : IFilterProvider
where T : FilterAttribute, new()
where TBaseT : FilterAttribute
{
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
var controllerType = controllerContext.Controller.GetType();
if (!controllerType.GetCustomAttributes(typeof(TBaseT), true).Any()
&& !actionDescriptor.GetCustomAttributes(typeof(TBaseT), true).Any())
{
yield return new Filter(new T(), FilterScope.Action, null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment