前言
上一节我们详细讲解了过滤器的创建过程以及粗略的介绍了五种过滤器,用此五种过滤器对实现对执行Action方法各个时期的拦截非常重要。这一节我们简单将讲述在Action方法上、控制器上、全局上以及授权上的自定义特性的执行过程。
APiController
之前有讲到该APiController,也就稍微介绍了,这节我们来详细此Web API控制器的基类:
public abstract class ApiController : IHttpController, IDisposable
{
// Fields
private HttpConfiguration _configuration;
private HttpControllerContext _controllerContext;
private bool _disposed;
private ModelStateDictionary _modelState;
private HttpRequestMessage _request;
private UrlHelper _urlHelper; // Methods
protected ApiController();
public void Dispose();
protected virtual void Dispose(bool disposing);
public virtual Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken);
protected virtual void Initialize(HttpControllerContext controllerContext);
internal static Func<Task<HttpResponseMessage>> InvokeActionWithActionFilters(HttpActionContext actionContext, CancellationToken cancellationToken, IEnumerable<IActionFilter> filters, Func<Task<HttpResponseMessage>> innerAction);
internal static Func<Task<HttpResponseMessage>> InvokeActionWithAuthorizationFilters(HttpActionContext actionContext, CancellationToken cancellationToken, IEnumerable<IAuthorizationFilter> filters, Func<Task<HttpResponseMessage>> innerAction);
internal static Task<HttpResponseMessage> InvokeActionWithExceptionFilters(Task<HttpResponseMessage> actionTask, HttpActionContext actionContext, CancellationToken cancellationToken, IEnumerable<IExceptionFilter> filters); // Properties
public HttpConfiguration Configuration { get; set; }
public HttpControllerContext ControllerContext { get; set; }
public ModelStateDictionary ModelState { get; }
public HttpRequestMessage Request { get; set; }
public UrlHelper Url { get; set; }
public IPrincipal User { get; } // Nested Types
private class FilterGrouping
{
// Fields
private List<IActionFilter> _actionFilters;
private List<IAuthorizationFilter> _authorizationFilters;
private List<IExceptionFilter> _exceptionFilters; // Methods
public FilterGrouping(IEnumerable<FilterInfo> filters);
private static void Categorize<T>(IFilter filter, List<T> list) where T: class; // Properties
public IEnumerable<IActionFilter> ActionFilters { get; }
public IEnumerable<IAuthorizationFilter> AuthorizationFilters { get; }
public IEnumerable<IExceptionFilter> ExceptionFilters { get; }
}
}
我们首先来看看此类中的一个私有类 FilterGrouping ,顾名思义是对过滤器分组,我们查看其构造函数看看:
public FilterGrouping(IEnumerable<FilterInfo> filters)
{
this._actionFilters = new List<IActionFilter>();
this._authorizationFilters = new List<IAuthorizationFilter>();
this._exceptionFilters = new List<IExceptionFilter>();
foreach (FilterInfo info in filters)
{
IFilter instance = info.Instance;
Categorize<IActionFilter>(instance, this._actionFilters);
Categorize<IAuthorizationFilter>(instance, this._authorizationFilters);
Categorize<IExceptionFilter>(instance, this._exceptionFilters);
}
}
我们仅仅只需 _actionFilters 为例,其余一样,我们再来看看 Categorize 方法:
private static void Categorize<T>(IFilter filter, List<T> list) where T: class
{
T item = filter as T;
if (item != null)
{
list.Add(item);
}
}
从这里我们可以得知:
当我们在HttpActionDescriptor初始化创建了封装了Filter对象的FilterInfo的集合列表,此时然后利用此类中的三个属性类型:IActionFilter、IAuthorizationFilter、以及IExceptionFilter进行过滤器分组得到对应过滤器集合列表
执行过程原理解析
下面我们通过例子来看看之执行过程,我们自定义以下五个过滤器
/// <summary>
/// 全局的行为过滤器
/// </summary>
public class CustomConfigurationActionFilterAttribute : FilterAttribute, IActionFilter
{
public Task<HttpResponseMessage> ExecuteActionFilterAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
Console.WriteLine(this.GetType().Name);
return continuation();
}
} /// <summary>
/// 控制器级行为过滤器
/// </summary>
public class CustomControllerActionFilterAttribute : FilterAttribute, IActionFilter
{
public Task<HttpResponseMessage> ExecuteActionFilterAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
Console.WriteLine(this.GetType().Name);
return continuation();
}
} /// <summary>
/// 控制器方法级行为过滤器
/// </summary>
public class CustomActionFilterAttribute : FilterAttribute, IActionFilter
{
public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
Console.WriteLine(this.GetType().Name);
return continuation();
}
} /// <summary>
/// 控制器级授权访问过滤器
/// </summary>
public class CustomControllerAuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter
{
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
Console.WriteLine(this.GetType().Name);
return continuation();
}
} /// <summary>
/// 控制器方法级授权访问过滤器
/// </summary>
public class CustomControllerActionAuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter
{
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
Console.WriteLine(this.GetType().Name);
return continuation();
}
}
接下来就是实现过滤器,配置文件中配置全局过滤器
config.Filters.Add(new CustomConfigurationActionFilterAttribute());
控制器及方法上过滤器
[CustomControllerAuthorizationFilter]
[CustomControllerActionFilter]
public class ProductController : ApiController
{
[CustomActionFilter]
[CustomControllerActionAuthorizationFilter]
public string GetFilter()
{
var sb = new StringBuilder(); var actionSelector = this.Configuration.Services.GetActionSelector();
var actionDesciptor = actionSelector.SelectAction(this.ControllerContext);
foreach (var filterInfo in actionDesciptor.GetFilterPipeline())
{
sb.AppendLine("【FilterName:" + filterInfo.Instance.GetType().Name + ",FilterScope:" + filterInfo.Scope.ToString() + "】");
}
return sb.ToString();
}
}
最后来查看其结果:
看到这里是不是有点疑惑怎么按照Global->Controller->Action来进行排序,如果你看过前面文章就会知道这是过滤器管道按照FilterScope来生成的,实际上在服务器端生成的顺序为 CustomControllerAuthorizationFilterAttribute 、 CustomControllerActionAuthorizationFilterAttribute 、 CustomConfigurationActionFilterAttribute 、 CustomControllerActionFilterAttribute 以及 CustomActionFilterAttribute 由此我们得出结论:
授权过滤器不管任何的FilterScope都是优于行为过滤器,而在同一种类型的过滤器中是根据FilterScope来确定执行顺序的。
总结
有关更多深入的内容就不再探讨,本想多写一点,但是状态不佳加上更多内容比较复杂以免说不太明白云里雾里,想想还是算了,就这样了,下面还是给出其一张执行的详细示意图,来源【过滤器执行过程】