You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.3 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using EntrustSettle.Common;
using EntrustSettle.Common.Http.HttpPolly;
using EntrustSettle.Model;
using Microsoft.Extensions.DependencyInjection;
using RestSharp;
using System;
namespace EntrustSettle.Extensions
{
/// <summary>
///
/// </summary>
public static class HttpClientSetup
{
public static void AddHttpClientSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
// Http请求方式1使用RestSharp
services.AddKeyedSingleton<IRestClient>(HttpEnum.Hyd, new RestClient(AppSettings.app("Apis", "Hyd", "BaseUrl")));
// Http请求方式2使用HttpClientFactory
//services.AddHttpClient(HttpEnum.Hyd.ToString(), c =>
//{
// c.BaseAddress = new Uri(AppSettings.app("Apis", "Hyd", "BaseUrl"));
//});
//services.AddSingleton<IHttpPollyHelper, HttpPollyHelper>();
//#region 方式2可配合Polly策略
//var retryPolicy = HttpPolicyExtensions
//.HandleTransientHttpError()
//.Or<TimeoutRejectedException>() // 若超时则抛出此异常
//.WaitAndRetryAsync(new[]
//{
// TimeSpan.FromSeconds(1),
// TimeSpan.FromSeconds(5),
// TimeSpan.FromSeconds(10)
//});
//// 为每个重试定义超时策略
//var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(10);
//services.AddHttpClient(HttpEnum.Common.ToString(), c =>
//{
// c.DefaultRequestHeaders.Add("Accept", "application/json");
//})
//.AddPolicyHandler(retryPolicy)
//// 将超时策略放在重试策略之内,每次重试会应用此超时策略
//.AddPolicyHandler(timeoutPolicy);
//services.AddHttpClient(HttpEnum.LocalHost.ToString(), c =>
//{
// c.BaseAddress = new Uri("http://www.localhost.com");
// c.DefaultRequestHeaders.Add("Accept", "application/json");
//})
//.AddPolicyHandler(retryPolicy)
//// 将超时策略放在重试策略之内,每次重试会应用此超时策略
//.AddPolicyHandler(timeoutPolicy);
//#endregion
}
}
}