1. 程式人生 > 其它 >filter過濾器實現

filter過濾器實現

問題場景:

對於處理介面返回值統一加密,過濾,特定值統一處理,統一返回等多種需求,net的攔截器前置攔截比較常用,例如:登入校驗,引數格式校驗等等。接下來介紹filter

filter過濾器實現

filter的ActionFilterAttribute可以做一定的處理,通過對OnActionExecuted的執行控制,來實現很多場景。ActionFilterAttribute類是C# ASP.net MVC中的過濾類,跟JAVA的Filter效果類似,但是Filter是介面。ActionFilterAttribute類是被abstract 修飾符修飾,表示該類只能是基類,也就是隻能被繼承。ActionFilterAttribute類中只有一個無引數的建構函式和四個被protected 修飾符修飾,表示該方法只限於本類和子類訪問,例項不能訪問。

 /// <summary>
    /// Service返回資料過濾器,為返回的資料增加返回碼和訊息
    /// </summary>
    public class ReturnDataFilterAttribute : ActionFilterAttribute
    {
        private static JsonMediaTypeFormatter _formatter;

        static ReturnDataFilterAttribute()
        {
            _formatter = new JsonMediaTypeFormatter();
            
//設定序列化器為json序列化器 // _formatter.UseDataContractJsonSerializer = true; //設定時間格式為Local _formatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local; _formatter.SerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffzz:00
"; //設定縮排 _formatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; //設定json格式為駝峰式 _formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response != null) { var oldResponse = actionExecutedContext.Response; //response狀態為請求成功 var result = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK); if (ApiMatch(ConfigHelper.GetAppSetting("IgnoreReturnDataFilter"), actionExecutedContext.Request.RequestUri.AbsolutePath)) { result.Content = oldResponse.Content; } else { object content = null; var objectContent = oldResponse.Content as ObjectContent; if (objectContent != null) { content = objectContent.Value; } //把action返回的值放到ReturnData的Result中 result.Content = new ObjectContent<ReturnData>( new ReturnData {Msg = "成功", Ret = CustomException.NoneError, Result = content}, _formatter); } actionExecutedContext.Response = result; } } /// <summary> /// API資料中的API是否匹配請求URIi /// </summary> /// <param name="apiArray">API資料</param> /// <param name="uri">請求URI</param> /// <returns>是否匹配</returns> private static bool ApiMatch(string apiArray, string uri) { var result = false; if (!string.IsNullOrWhiteSpace(apiArray)) { var apiList = apiArray.ToLower().Split(','); string uriLower = uri.ToLower(); foreach (var api in apiList) { if (api == uriLower || api + "/" == uriLower) { result = true; break; } } } return result; } }
     //返回資料過濾器
    config.Filters.Add(new ReturnDataFilterAttribute());