Exemplo n.º 1
0
 /// <summary>
 /// 设置客户端信息
 /// </summary>
 /// <param name="method"></param>
 /// <param name="httpClientPart"></param>
 /// <param name="declaringType"></param>
 private static void SetClient(MethodInfo method, HttpClientPart httpClientPart, Type declaringType)
 {
     // 设置 Client 名称,判断方法是否定义,如果没有再查找声明类
     var clientAttribute = method.IsDefined(typeof(ClientAttribute), true)
         ? method.GetCustomAttribute <ClientAttribute>(true)
         : (
         declaringType.IsDefined(typeof(ClientAttribute), true)
             ? declaringType.GetCustomAttribute <ClientAttribute>(true)
             : default
Exemplo n.º 2
0
        /// <summary>
        /// 构建 HttpClient 请求部件
        /// </summary>
        /// <param name="method"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private static HttpClientPart BuildHttpClientPart(MethodInfo method, object[] args)
        {
            // 判断方法是否是远程代理请求方法
            if (!method.IsDefined(typeof(HttpMethodBaseAttribute), true))
            {
                throw new InvalidOperationException($"{method.Name} is not a valid request proxy method.");
            }

            // 解析方法参数及参数值
            var parameters = method.GetParameters().Select((u, i) => new MethodParameterInfo
            {
                Parameter = u,
                Name      = u.Name,
                Value     = args[i]
            });

            // 获取请求配置
            var httpMethodBase = method.GetCustomAttribute <HttpMethodBaseAttribute>(true);

            // 创建请求配置对象
            var httpClientPart = new HttpClientPart();

            httpClientPart.SetRequestUrl(httpMethodBase.RequestUrl)
            .SetHttpMethod(httpMethodBase.Method)
            .SetTemplates(parameters.ToDictionary(u => u.Name, u => u.Value));

            // 获取方法所在类型
            var declaringType = method.DeclaringType;

            // 设置请求客户端
            SetClient(method, httpClientPart, declaringType);

            // 设置请求报文头
            SetHeaders(method, parameters, httpClientPart, declaringType);

            // 设置 Url 地址参数
            SetQueries(parameters, httpClientPart);

            // 设置 Body 信息
            SetBody(parameters, httpClientPart);

            // 设置验证
            SetValidation(parameters);

            // 设置序列化
            SetJsonSerialization(method, parameters, httpClientPart, declaringType);

            // 配置全局拦截
            CallGlobalInterceptors(httpClientPart, declaringType);

            // 设置请求拦截
            SetInterceptors(parameters, httpClientPart);

            return(httpClientPart);
        }