/// <summary>
        /// 异步POST请求
        /// </summary>
        /// <typeparam name="TModel">提交类型</typeparam>
        /// <typeparam name="TResult">返回类型</typeparam>
        /// <param name="httpMessageService"><see cref="IHttpMessageService"/>操作服务</param>
        /// <param name="urlArguments"><see cref="UrlArguments"/>Url构造器</param>
        /// <param name="model">提交的模型数据</param>
        /// <param name="mediaType">请求返回的数据类型<see cref="HttpMediaType"/></param>
        /// <param name="options">序列化方式<see cref="MessagePackSerializerResolver"/>,如果是JSON不需要设置</param>
        /// <param name="clientHandler"><see cref="HttpClient"/>回调,可以添加需要的Header等</param>
        /// <param name="errorHandler"><see cref="HttpResponseMessage"/>请求异常处理,默认情况返回错误的Return模型</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static async Task <TResult> PostAsync <TModel, TResult>(this IHttpMessageService httpMessageService, UrlArguments urlArguments, TModel model,
                                                                       HttpMediaType mediaType = HttpMediaType.Json, MessagePackSerializerOptions options = null, Action <HttpClient> clientHandler = null, Func <HttpResponseMessage, TResult> errorHandler = null, CancellationToken cancellationToken = default)
        {
            options = options ?? MessagePackSerializerResolver.DateTimeOptions;

            var client = httpMessageService.CreateClient(urlArguments.ClientName)
                         .SetHeaderAccept(mediaType);

            if (clientHandler != null)
            {
                clientHandler.Invoke(client);
            }

            var responseMessage = await client.PostAsync(urlArguments, model, cancellationToken);

            if (!responseMessage.IsSuccessStatusCode)
            {
                return(errorHandler == null ? default : errorHandler.Invoke(responseMessage));
            }
            else
            {
                return(await responseMessage.Content.ReadAsAsync <TResult>(mediaType, options));
            }
        }
        public static async Task <TModel> ReadAsAsync <TModel>(this HttpContent httpContent, HttpMediaType mediaType, MessagePackSerializerOptions options = null)
        {
            switch (mediaType)
            {
            case HttpMediaType.MessagePack:
            {
                var res = await httpContent.ReadAsByteArrayAsync();

                return(res.ToMsgPackObject <TModel>(options));
            }

            case HttpMediaType.MessagePackJackson:
            {
                var res = await httpContent.ReadAsStringAsync();

                return(res.ToMsgPackBytesFromJson(options).ToMsgPackObject <TModel>(options));
            }

            default:
            {
                var res = await httpContent.ReadAsStringAsync();

                return(res.ToObject <TModel>());
            }
            }
        }
        public static HttpContent Create <TModel>(TModel model, Encoding encoding = null, HttpMediaType mediaType = HttpMediaType.Json)
        {
            HttpContent content;

            switch (mediaType)
            {
            case HttpMediaType.MessagePack:
                content = new ByteArrayContent(model.ToMsgPackBytes());
                break;

            default:
                content = new StringContent(model.ToJson(), encoding ?? Encoding.UTF8);
                break;
            }

            content.Headers.ContentType = new MediaTypeHeaderValue(mediaType.Description());

            return(content);
        }
Esempio n. 4
0
        public static HttpRequestMessage SetHeaderAccept(this HttpRequestMessage request, HttpMediaType mediaType)
        {
            request.SetHeaderAccept(mediaType.Description());

            return(request);
        }
Esempio n. 5
0
        public static HttpClient SetHeaderAccept(this HttpClient client, HttpMediaType mediaType)
        {
            client.SetHeaderAccept(mediaType.Description());

            return(client);
        }
Esempio n. 6
0
 /// <summary>
 /// POST提交数据
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <typeparam name="TModel"></typeparam>
 /// <param name="urlArguments">Url构造器</param>
 /// <param name="postData">模型数据</param>
 /// <param name="mediaType">mediaType数据格式,请求格式和返回格式一致(JSON、MessagePack)</param>
 /// <param name="cancellationToken">取消令牌</param>
 /// <returns></returns>
 public async Task <T> PostAsync <T, TModel>(UrlArguments urlArguments, TModel postData, HttpMediaType mediaType, CancellationToken cancellationToken = default)
     where T : class, new()
 => await HttpSendAsync <T, TModel>(urlArguments, HttpMethod.Post, postData, mediaType, cancellationToken);
Esempio n. 7
0
 /// <summary>
 /// GET请求数据
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="urlArguments">Url构造器</param>
 /// <param name="mediaType">mediaType数据格式,请求格式和返回格式一致(JSON、MessagePack)</param>
 /// <param name="cancellationToken">取消令牌</param>
 /// <returns></returns>
 public async Task <T> GetAsync <T>(UrlArguments urlArguments, HttpMediaType mediaType, CancellationToken cancellationToken = default)
     where T : class, new()
 => await HttpSendAsync <T>(urlArguments, HttpMethod.Get, null, mediaType, cancellationToken);
Esempio n. 8
0
        /// <summary>
        /// 发送请求数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="urlArguments">Url构造器</param>
        /// <param name="method">请求类型</param>
        /// <param name="contentCall">HttpContent请求内容</param>
        /// <param name="mediaType">mediaType数据格式,请求格式和返回格式一致(JSON、MessagePack)</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public virtual async Task <T> HttpSendAsync <T>(UrlArguments urlArguments, HttpMethod method, Func <HttpContent> contentCall, HttpMediaType mediaType = HttpMediaType.Json, CancellationToken cancellationToken = default)
            where T : class, new()
        {
            HttpClient client = HttpClientFactory.CreateClient(string.IsNullOrEmpty(urlArguments.ClientName) ? "apiClient" : urlArguments.ClientName);

            string requestUrl = urlArguments.Complete().Url;

            string _mediaType = mediaType.Description();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_mediaType));

            HttpResponseMessage responseMessage = null;

            if (client.BaseAddress == null)
            {
                HttpRequestMessage requestMessage = new HttpRequestMessage
                {
                    Method     = method,
                    RequestUri = new Uri(requestUrl)
                };

                foreach (var accept in client.DefaultRequestHeaders.Accept)
                {
                    requestMessage.Headers.Accept.Add(accept);
                }

                requestMessage.Headers.Authorization = client.DefaultRequestHeaders.Authorization;

                RequestHeaders(requestMessage.Headers);

                requestMessage.Content = contentCall?.Invoke();
                //if (requestMessage.Content != null)
                //    requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(_mediaType);

                responseMessage = await client.SendAsync(requestMessage, cancellationToken);
            }
            else
            {
                RequestHeaders(client.DefaultRequestHeaders);

                HttpContent content = contentCall?.Invoke();
                //if (content != null)
                //    content.Headers.ContentType = new MediaTypeHeaderValue(_mediaType);

                responseMessage = await SendAsync(client, requestUrl, method, content, cancellationToken);
            }

            switch (mediaType)
            {
            case HttpMediaType.MessagePack:
            {
                var res = await responseMessage.Content.ReadAsByteArrayAsync();

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation($"{client.BaseAddress}{requestUrl} MediaType:{_mediaType},Method:{method.Method},HttpMessage Read Byte Data Length:{res.Length}");
                }

                return(res.ToMsgPackObject <T>());
            }

            case HttpMediaType.MessagePackJackson:
            {
                var res = await responseMessage.Content.ReadAsStringAsync();

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug($"{client.BaseAddress}{requestUrl} MediaType:{_mediaType},Method:{method.Method},HttpMessage Read Jackson Data:{res}");
                }

                return(res.ToMsgPackBytesFromJson().ToMsgPackObject <T>());
            }

            default:
            {
                var res = await responseMessage.Content.ReadAsStringAsync();

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation($"{client.BaseAddress}{requestUrl} MediaType:{_mediaType},Method:{method.Method},HttpMessage Read Json Data:{res}");
                }

                return(res.ToObject <T>());
            }
            }
        }
Esempio n. 9
0
 /// <summary>
 /// 发送请求数据
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <typeparam name="TModel"></typeparam>
 /// <param name="urlArguments">Url构造器</param>
 /// <param name="method">请求类型</param>
 /// <param name="postData">模型数据</param>
 /// <param name="mediaType">mediaType数据格式,请求格式和返回格式一致(JSON、MessagePack)</param>
 /// <param name="cancellationToken">取消令牌</param>
 /// <returns></returns>
 public async Task <T> HttpSendAsync <T, TModel>(UrlArguments urlArguments, HttpMethod method, TModel postData, HttpMediaType mediaType = HttpMediaType.Json, CancellationToken cancellationToken = default)
     where T : class, new()
 => await HttpSendAsync <T>(urlArguments, method, () => postData == null?null : new StringContent(postData.ToJson(), Encoding.UTF8, "application/json"), mediaType, cancellationToken);
Esempio n. 10
0
 public HttpContentTypeHeader(HttpMediaType mediaType)
 {
     MediaType = mediaType;
 }
Esempio n. 11
0
 public HttpContentTypeHeader(string mediaType)
 {
     MediaType = HttpMediaType.Parse(mediaType ?? throw new ArgumentNullException(nameof(mediaType)));
 }