问题场景:
对于处理接口返回值统一加密,过滤,特定值统一处理,统一返回等多种需求,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());