/// <summary> /// 设置请求拦截 /// </summary> /// <param name="parameters"></param> /// <param name="httpRequestPart"></param> private static void SetInterceptors(IEnumerable <MethodParameterInfo> parameters, HttpRequestPart httpRequestPart) { // 添加方法拦截器 var Interceptors = parameters.Where(u => u.Parameter.IsDefined(typeof(InterceptorAttribute), true)); foreach (var item in Interceptors) { // 获取拦截器类型 var interceptor = item.Parameter.GetCustomAttribute <InterceptorAttribute>(); switch (interceptor.Type) { // 加载请求拦截 case InterceptorTypes.Request: if (item.Value is Action <HttpRequestMessage> onRequesting) { httpRequestPart.OnRequesting(onRequesting); } break; // 加载响应拦截 case InterceptorTypes.Response: if (item.Value is Action <HttpResponseMessage> onResponsing) { httpRequestPart.OnResponsing(onResponsing); } break; // 加载 Client 配置拦截 case InterceptorTypes.Client: if (item.Value is Action <HttpClient> onClientCreating) { httpRequestPart.OnClientCreating(onClientCreating); } break; // 加载异常拦截 case InterceptorTypes.Exception: if (item.Value is Action <HttpResponseMessage, string> onException) { httpRequestPart.OnException(onException); } break; default: break; } } }
/// <summary> /// 调用全局拦截 /// </summary> /// <param name="httpRequestPart"></param> /// <param name="declaringType"></param> private static void CallGlobalInterceptors(HttpRequestPart httpRequestPart, Type declaringType) { // 获取所有静态方法且贴有 [Interceptor] 特性 var interceptorMethods = declaringType.GetMethods() .Where(u => u.IsDefined(typeof(InterceptorAttribute), true)); foreach (var method in interceptorMethods) { // 获取拦截器类型 var interceptor = method.GetCustomAttributes <InterceptorAttribute>().First(); switch (interceptor.Type) { // 加载请求拦截 case InterceptorTypes.Request: var onRequesting = (Action <HttpRequestMessage>)Delegate.CreateDelegate(typeof(Action <HttpRequestMessage>), method); httpRequestPart.OnRequesting(onRequesting); break; // 加载响应拦截 case InterceptorTypes.Response: var onResponsing = (Action <HttpResponseMessage>)Delegate.CreateDelegate(typeof(Action <HttpResponseMessage>), method); httpRequestPart.OnResponsing(onResponsing); break; // 加载 Client 配置拦截 case InterceptorTypes.Client: var onClientCreating = (Action <HttpClient>)Delegate.CreateDelegate(typeof(Action <HttpClient>), method); httpRequestPart.OnClientCreating(onClientCreating); break; // 加载异常拦截 case InterceptorTypes.Exception: var onException = (Action <HttpResponseMessage, string>)Delegate.CreateDelegate(typeof(Action <HttpResponseMessage, string>), method); httpRequestPart.OnException(onException); break; default: break; } } }