巧用ActionFilter的AOP特性,为返回的数据增加返回码和消息
生活随笔
收集整理的這篇文章主要介紹了
巧用ActionFilter的AOP特性,为返回的数据增加返回码和消息
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景
對于處理接口返回值統一加密,過濾,特定值統一處理,統一返回等多種需求,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());總結
以上是生活随笔為你收集整理的巧用ActionFilter的AOP特性,为返回的数据增加返回码和消息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Blazor中的无状态组件
- 下一篇: 解读WPF中的Xaml