Ejemplo n.º 1
0
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        async Task IApiParameterable.BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var keyValue    = new KeyValuePair <string, string>(parameter.Name, this.stringValue);
            var httpContent = await context.EnsureNoGet().RequestMessage.Content.MergeKeyValuesAsync(new[] { keyValue });

            context.RequestMessage.Content = httpContent;

            await TaskExtend.CompletedTask;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        public async Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var ables = this.GetApiParameterables(parameter);

            foreach (var item in ables)
            {
                await item?.BeforeRequestAsync(context, parameter);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        async Task IApiParameterable.BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var httpContent = context.EnsureNoGet().RequestMessage.Content.CastOrCreateMultipartContent();

            httpContent.AddText(parameter.Name, this.stringValue);
            context.RequestMessage.Content = httpContent;

            await TaskExtend.CompletedTask;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 获取异步结果
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns></returns>
        public override async Task <object> GetTaskResult(ApiActionContext context)
        {
            var response = context.ResponseMessage;
            var json     = await response.Content.ReadAsStringAsync();

            var dataType = context.ApiActionDescriptor.ReturnDataType;
            var result   = context.HttpApiClient.JsonFormatter.Deserialize(json, dataType);

            return(result);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        Task IApiParameterable.BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var header = context.RequestMessage.Headers;

            header.Remove(scheme);
            if (this.authValue != null)
            {
                header.TryAddWithoutValidation(scheme, this.authValue);
            }
            return(ApiTask.CompletedTask);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 获取http请求内容
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        protected override HttpContent GetHttpContent(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var xmlSerializer = new XmlSerializer(parameter.ParameterType);

            using (var stream = new MemoryStream())
            {
                xmlSerializer.Serialize(stream, parameter.Value);
                var xml = Encoding.UTF8.GetString(stream.ToArray());
                return(new StringContent(xml, Encoding.UTF8, "application/xml"));
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        public sealed override async Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            if (context.RequestMessage.Method == HttpMethod.Get)
            {
                return;
            }

            var httpContent = this.GetHttpContent(context, parameter);

            context.RequestMessage.Content = httpContent;
            await TaskExtend.CompletedTask;
        }
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        public async Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var ables = this.GetApiParameterables(parameter);

            foreach (var item in ables)
            {
                if (item != null)
                {
                    await item.BeforeRequestAsync(context, parameter).ConfigureAwait(false);
                }
            }
        }
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        public void BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var ables = this.GetApiParameterables(parameter);

            foreach (var item in ables)
            {
                if (item != null)
                {
                    item.BeforeRequestAsync(context, parameter);
                }
            }
        }
Ejemplo n.º 10
0
            /// <summary>
            /// 执行一次请求
            /// </summary>
            /// <returns></returns>
            private async Task <TResult> RequestAsync()
            {
                var context = new ApiActionContext
                {
                    HttpApiConfig       = this.httpApiConfig,
                    ApiActionDescriptor = this.apiActionDescriptor,
                    RequestMessage      = new HttpApiRequestMessage {
                        RequestUri = this.httpApiConfig.HttpHost
                    }
                };

                return(await context.ExecuteActionAsync <TResult>().ConfigureAwait(false));
            }
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        public Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var fileInfo = parameter.Value as FileInfo;

            if (fileInfo != null)
            {
                var stream          = fileInfo.Open(FileMode.Open, FileAccess.Read);
                var fileName        = Path.GetFileName(fileInfo.FullName);
                var encodedFileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
                context.RequestMessage.AddMulitpartFile(stream, parameter.Name, encodedFileName, null);
            }
            return(ApiTask.CompletedTask);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        public override async Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            if (this.IgnoreWhenNull && parameter.Value == null)
            {
                return;
            }

            var uri       = context.RequestMessage.RequestUri;
            var pathQuery = this.GetPathQuery(uri.LocalPath + uri.Query, parameter);

            context.RequestMessage.RequestUri = new Uri(uri, pathQuery);
            await TaskEx.CompletedTask;
        }
Ejemplo n.º 13
0
 /// <summary>
 /// http请求之前
 /// </summary>
 /// <param name="context">上下文</param>
 /// <param name="parameter">特性关联的参数</param>
 /// <returns></returns>
 public async Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
 {
     if (parameter.Value is IApiParameterable able)
     {
         await able.BeforeRequestAsync(context, parameter).ConfigureAwait(false);
     }
     else if (parameter.Value is IEnumerable <IApiParameterable> array)
     {
         foreach (var item in array)
         {
             await item.BeforeRequestAsync(context, parameter).ConfigureAwait(false);
         }
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// 获取异步结果
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns></returns>
        public override async Task <object> GetTaskResult(ApiActionContext context)
        {
            var response      = context.ResponseMessage;
            var dataType      = context.ApiActionDescriptor.ReturnDataType;
            var xmlSerializer = new XmlSerializer(dataType);

            using (var stream = new MemoryStream())
            {
                await response.Content.CopyToAsync(stream);

                stream.Position = 0;
                return(xmlSerializer.Deserialize(stream));
            }
        }
Ejemplo n.º 15
0
            /// <summary>
            /// 创建请求任务
            /// </summary>
            /// <returns></returns>
            async Task <TResult> ITask <TResult> .InvokeAsync()
            {
                var context = new ApiActionContext
                {
                    ApiActionDescriptor = this.apiActionDescriptor,
                    HttpApiConfig       = this.httpApiConfig,
                    RequestMessage      = new HttpApiRequestMessage {
                        RequestUri = this.httpApiConfig.HttpHost
                    },
                    ResponseMessage = null
                };

                return((TResult)await this.apiActionDescriptor.ExecuteAsync(context));
            }
Ejemplo n.º 16
0
            /// <summary>
            /// 执行一次请求
            /// </summary>
            /// <returns></returns>
            private async Task <TResult> RequestAsync()
            {
                var context = new ApiActionContext
                {
                    ApiActionDescriptor = this.apiActionDescriptor,
                    HttpApiConfig       = this.httpApiConfig,
                    RequestMessage      = new HttpApiRequestMessage {
                        RequestUri = this.httpApiConfig.HttpHost
                    },
                    ResponseMessage = null
                };
                var result = await this.RequestAsync(context);

                return((TResult)result);
            }
Ejemplo n.º 17
0
        /// <summary>
        /// 执行请求前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的属性</param>
        async Task IApiParameterable.BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var method = context.RequestMessage.Method;

            if (method == HttpMethod.Get || method == HttpMethod.Head)
            {
                return;
            }

            var httpContent = context.RequestMessage.Content.CastMultipartContent();
            var fileContent = new MulitpartFileContent(this.GetStream(), parameter.Name, this.FileName, this.ContentType);

            httpContent.Add(fileContent);
            context.RequestMessage.Content = httpContent;
            await TaskExtend.CompletedTask;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 执行请求前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        async Task IApiParameterable.BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var method = context.RequestMessage.Method;

            if (method == HttpMethod.Get || method == HttpMethod.Head)
            {
                var message = string.Format("{0}方法不支持使用{1}", method, this.GetType().Name);
                throw new NotSupportedException(message);
            }

            var httpContent = context.RequestMessage.Content.CastOrCreateMultipartContent();

            httpContent.AddFile(this.GetStream(), parameter.Name, this.FileName, this.ContentType);
            context.RequestMessage.Content = httpContent;
            await TaskExtend.CompletedTask;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// http请求之前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        async Task IApiParameterable.BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var method = context.RequestMessage.Method;

            if (method == HttpMethod.Get || method == HttpMethod.Head)
            {
                var message = string.Format("{0}方法不支持使用{1}", method, this.GetType().Name);
                throw new NotSupportedException(message);
            }

            var keyValue    = new KeyValuePair <string, string>(parameter.Name, this.stringValue);
            var httpContent = await context.RequestMessage.Content.MergeKeyValuesAsync(new[] { keyValue });

            context.RequestMessage.Content = httpContent;

            await TaskExtend.CompletedTask;
        }
Ejemplo n.º 20
0
            /// <summary>
            /// 异步执行http请求
            /// </summary>
            /// <param name="context">上下文</param>
            /// <returns></returns>
            private async Task <object> RequestAsync(ApiActionContext context)
            {
                var apiAction     = context.ApiActionDescriptor;
                var globalFilters = context.HttpApiConfig.GlobalFilters;

                foreach (var actionAttribute in apiAction.Attributes)
                {
                    await actionAttribute.BeforeRequestAsync(context);
                }

                foreach (var parameter in apiAction.Parameters)
                {
                    foreach (var parameterAttribute in parameter.Attributes)
                    {
                        await parameterAttribute.BeforeRequestAsync(context, parameter);
                    }
                }

                foreach (var filter in globalFilters)
                {
                    await filter.OnBeginRequestAsync(context);
                }

                foreach (var filter in apiAction.Filters)
                {
                    await filter.OnBeginRequestAsync(context);
                }

                var client = context.HttpApiConfig.HttpClient;

                context.ResponseMessage = await client.SendAsync(context.RequestMessage);

                foreach (var filter in globalFilters)
                {
                    await filter.OnEndRequestAsync(context);
                }

                foreach (var filter in apiAction.Filters)
                {
                    await filter.OnEndRequestAsync(context);
                }

                return(await apiAction.Return.Attribute.GetTaskResult(context));
            }
Ejemplo n.º 21
0
        /// <summary>
        /// 异步执行api
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns></returns>
        public async Task <object> ExecuteAsync(ApiActionContext context)
        {
            var apiAction     = context.ApiActionDescriptor;
            var globalFilters = context.HttpApiConfig.GlobalFilters;

            foreach (var actionAttribute in apiAction.Attributes)
            {
                await actionAttribute.BeforeRequestAsync(context);
            }

            foreach (var parameter in apiAction.Parameters)
            {
                foreach (var parameterAttribute in parameter.Attributes)
                {
                    await parameterAttribute.BeforeRequestAsync(context, parameter);
                }
            }

            foreach (var filter in globalFilters)
            {
                await filter.OnBeginRequestAsync(context);
            }

            foreach (var filter in apiAction.Filters)
            {
                await filter.OnBeginRequestAsync(context);
            }

            await this.SendAsync(context);

            foreach (var filter in globalFilters)
            {
                await filter.OnEndRequestAsync(context);
            }

            foreach (var filter in apiAction.Filters)
            {
                await filter.OnEndRequestAsync(context);
            }

            return(await apiAction.Return.Attribute.GetTaskResult(context));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 执行Http请求接口
        /// </summary>
        /// <param name="invocation">上下文</param>
        /// <returns></returns>
        private Task ExecuteHttpApi(IInvocation invocation)
        {
            var cache            = DescriptorCache.GetApiActionDescriptor(invocation);
            var actionDescripter = cache.Clone() as ApiActionDescriptor;

            for (var i = 0; i < actionDescripter.Parameters.Length; i++)
            {
                actionDescripter.Parameters[i].Value = invocation.GetArgumentValue(i);
            }

            var actionContext = new ApiActionContext
            {
                ApiActionDescriptor = actionDescripter,
                HttpApiConfig       = this.httpApiConfig,
                RequestMessage      = new HttpRequestMessage(HttpMethod.Get, this.httpApiConfig.HttpHost),
                ResponseMessage     = null
            };

            return(actionDescripter.Execute(actionContext));
        }
Ejemplo n.º 23
0
        ///// <summary>
        ///// 获取ITaskOf(dataType)的构造器
        ///// </summary>
        ///// <param name="dataType">泛型参数类型</param>
        ///// <returns></returns>
        //public static ConstructorInfo GetITaskConstructor(Type dataType)
        //{
        //    return typeof(ApiTaskOf<>)
        //        .MakeGenericType(dataType)
        //        .GetConstructor(new[] { typeof(HttpApiConfig), typeof(ApiActionDescriptor) });
        //}

        /// <summary>
        /// 创建ApiTaskOf(T)的实例
        /// </summary>
        /// <param name="httpApiConfig">http接口配置</param>
        /// <param name="apiActionDescriptor">api描述</param>
        /// <returns></returns>
        public static object CreateInstance(HttpApiConfig httpApiConfig, ApiActionDescriptor apiActionDescriptor)
        {
            var context = new ApiActionContext
            {
                ApiActionDescriptor = apiActionDescriptor,
                HttpApiConfig       = httpApiConfig,
                RequestMessage      = new HttpApiRequestMessage {
                    RequestUri = httpApiConfig.HttpHost
                },
                ResponseMessage = null,
                Exception       = null,
                Result          = null
            };

            context.PrepareRequestAsync();

            context.ExecRequestAsync();

            return(context.Result);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 获取异步结果
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns></returns>
        public override async Task <object> GetTaskResult(ApiActionContext context)
        {
            var response   = context.ResponseMessage;
            var returnType = context.ApiActionDescriptor.ReturnDataType;

            if (returnType == typeof(HttpResponseMessage))
            {
                return(response);
            }

            if (returnType == typeof(byte[]))
            {
                return(await response.Content.ReadAsByteArrayAsync());
            }

            if (returnType == typeof(string))
            {
                return(await response.Content.ReadAsStringAsync());
            }

            var message = string.Format("不支持的类型{0}的解析", returnType);

            throw new NotSupportedException(message);
        }
Ejemplo n.º 25
0
            /// <summary>
            /// 执行一次请求
            /// </summary>
            /// <returns></returns>
            private async Task <TResult> RequestAsync()
            {
                var context = new ApiActionContext
                {
                    ApiActionDescriptor = this.apiActionDescriptor,
                    HttpApiConfig       = this.httpApiConfig,
                    RequestMessage      = new HttpApiRequestMessage {
                        RequestUri = this.httpApiConfig.HttpHost
                    },
                    ResponseMessage = null,
                    Exception       = null,
                    Result          = null
                };

                await context.PrepareRequestAsync().ConfigureAwait(false);

                await context.ExecFiltersAsync(filter => filter.OnBeginRequestAsync).ConfigureAwait(false);

                var state = await context.ExecRequestAsync().ConfigureAwait(false);

                await context.ExecFiltersAsync(filter => filter.OnEndRequestAsync).ConfigureAwait(false);

                return(state ? (TResult)context.Result : throw context.Exception);
            }
Ejemplo n.º 26
0
        /// <summary>
        /// 方法拦截
        /// </summary>
        /// <param name="invocation">拦截内容</param>
        void IInterceptor.Intercept(IInvocation invocation)
        {
            var context       = CastleContext.From(invocation);
            var actionContext = new ApiActionContext
            {
                HttpApiClient             = this,
                RequestMessage            = new HttpRequestMessage(),
                HostAttribute             = context.HostAttribute,
                ApiReturnAttribute        = context.ApiReturnAttribute,
                ApiActionFilterAttributes = context.ApiActionFilterAttributes,
                ApiActionDescriptor       = context.ApiActionDescriptor.Clone() as ApiActionDescriptor
            };

            var parameters = actionContext.ApiActionDescriptor.Parameters;

            for (var i = 0; i < parameters.Length; i++)
            {
                parameters[i].Value = invocation.Arguments[i];
            }

            var apiAction = context.ApiActionDescriptor;

            invocation.ReturnValue = apiAction.Execute(actionContext);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// 执行前
 /// </summary>
 /// <param name="context">上下文</param>
 /// <returns></returns>
 public override Task BeforeRequestAsync(ApiActionContext context)
 {
     context.RequestMessage.Method     = this.Method;
     context.RequestMessage.RequestUri = new Uri(context.HostAttribute.Host, this.Path);
     return(TaskEx.CompletedTask);
 }
Ejemplo n.º 28
0
 /// <summary>
 /// http请求之前
 /// </summary>
 /// <param name="context">上下文</param>
 /// <param name="parameter">特性关联的参数</param>
 /// <returns></returns>
 public abstract Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter);
Ejemplo n.º 29
0
        /// <summary>
        /// 获取http请求内容
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="parameter">特性关联的参数</param>
        /// <returns></returns>
        protected override HttpContent GetHttpContent(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            var json = parameter.Value == null ? null : context.HttpApiClient.JsonFormatter.Serialize(parameter.Value);

            return(new StringContent(json, Encoding.UTF8, "application/json"));
        }
Ejemplo n.º 30
0
 /// <summary>
 /// JsonRpc请求内容
 /// </summary>
 /// <param name="context">请求上下文</param>
 /// <param name="jsonRpcMethod">请求方法特性</param>
 public JsonRpcContent(ApiActionContext context, JsonRpcMethodAttribute jsonRpcMethod)
 {
     this.context             = context;
     this.jsonRpcMethod       = jsonRpcMethod;
     this.Headers.ContentType = new MediaTypeHeaderValue(jsonRpcMethod.ContentType ?? JsonRpc.ContentType);
 }