filter的介紹
filter在Web API中經常會用到,主要用於記錄日志,安全驗證,全局錯誤處理等;Web API提供兩種過濾器的基本類型:actionfilterattribute,exceptionfilterattribute;兩個類都是抽象類,actionfilter主要實現執行請求方法體之前(覆蓋基類方法OnActionExecuting),和之后的事件處理(覆蓋基類方法OnActionExecuted);exceptionfilter主要實現觸發異常方法(覆蓋基類方法OnException)。下面對前者類型做示例。
新建ActionFilter類
打印參數、返回值、以及接口響應時間:
public class ActionFilter : ActionFilterAttribute
{
private const string Key = "action";
private bool _IsDebugLog = true;
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (_IsDebugLog)
{
Stopwatch stopWatch = new Stopwatch();
actionContext.Request.Properties[Key] = stopWatch;
string actionName = actionContext.ActionDescriptor.ActionName;
Debug.Print(Newtonsoft.Json.JsonConvert.SerializeObject(actionContext.ActionArguments));
stopWatch.Start();
}
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (_IsDebugLog)
{
Stopwatch stopWatch = actionExecutedContext.Request.Properties[Key] as Stopwatch;
if (stopWatch != null)
{
stopWatch.Stop();
string actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
string controllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
Debug.Print(actionExecutedContext.Response.Content.ReadAsStringAsync().Result);
Debug.Print(string.Format(@"[{0}/{1} 用時 {2}ms]", controllerName, actionName, stopWatch.Elapsed.TotalMilliseconds));
}
}
}
}
在接口的action方法上添加過濾器
[ActionFilter]

或者將過濾器添加到配置中,這樣將相當於在每個接口上添加了過濾器

演示
發送請求:

接口響應:


