Skip to content

Commit

Permalink
Use build-in httpclient instead of AgileHttp;
Browse files Browse the repository at this point in the history
  • Loading branch information
agile.zhou committed Nov 26, 2023
1 parent 435687d commit fe86291
Show file tree
Hide file tree
Showing 14 changed files with 261 additions and 141 deletions.
22 changes: 20 additions & 2 deletions src/AgileConfig.Server.Apisite/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using AgileConfig.Server.Apisite.UIExtension;
using AgileConfig.Server.Apisite.Websocket;
using AgileConfig.Server.Common;
using AgileConfig.Server.Common.RestClient;
using AgileConfig.Server.Data.Freesql;
using AgileConfig.Server.OIDC;
using AgileConfig.Server.Service;
Expand All @@ -27,13 +29,23 @@ public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
Configuration = configuration;
Global.LoggerFactory = loggerFactory;

TrustSSL(configuration);
SetTrustSSL(configuration);
}

private void TrustSSL(IConfiguration configuration)
private static bool IsTrustSSL(IConfiguration configuration)
{
var alwaysTrustSsl = configuration["alwaysTrustSsl"];
if (!string.IsNullOrEmpty(alwaysTrustSsl) && alwaysTrustSsl.ToLower() == "true")
{
return true;
}

return false;
}

private static void SetTrustSSL(IConfiguration configuration)
{
if (IsTrustSSL(configuration))
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
}
Expand All @@ -47,6 +59,9 @@ public IConfiguration Configuration
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDefaultHttpClient(IsTrustSSL(Configuration));
services.AddRestClient();

var jwtService = new JwtService();
services.AddMemoryCache();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
Expand All @@ -71,6 +86,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddBusinessServices();
services.AddHostedService<InitService>();
services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = true);

services.AddOIDC();
}

Expand Down Expand Up @@ -138,5 +154,7 @@ private void AddSwaggerMiddleWare(IApplicationBuilder app)
c.SwaggerEndpoint("v1/swagger.json", "My API V1");
});
}


}
}
32 changes: 32 additions & 0 deletions src/AgileConfig.Server.Apisite/StartupExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using AgileConfig.Server.Common;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http;

namespace AgileConfig.Server.Apisite
{
public static class StartupExtension
{
public static void AddDefaultHttpClient(this IServiceCollection services, bool isTrustSSL)
{
services.AddHttpClient(Global.DefaultHttpClientName)
.ConfigurePrimaryHttpMessageHandler(() => {
return NewMessageHandler(isTrustSSL);
})
;
}

static HttpMessageHandler NewMessageHandler(bool alwaysTrustSsl)
{
var handler = new HttpClientHandler();
if (alwaysTrustSsl)
{
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
return true;
};
}

return handler;
}
}
}
2 changes: 2 additions & 0 deletions src/AgileConfig.Server.Common/Global.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,7 @@ public static ILoggerFactory LoggerFactory
_loggerFactory = value;
}
}

public const string DefaultHttpClientName = "Default";
}
}
82 changes: 82 additions & 0 deletions src/AgileConfig.Server.Common/RestClient/DefaultRestClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace AgileConfig.Server.Common.RestClient
{
public class DefaultRestClient : IRestClient
{
private readonly IHttpClientFactory _httpClientFactory;

public DefaultRestClient(
IHttpClientFactory httpClientFactory
)
{
this._httpClientFactory = httpClientFactory;
}

private HttpClient GetDefaultClient()
{
return _httpClientFactory.CreateClient(Global.DefaultHttpClientName);
}

public async Task<T> GetAsync<T>(string url, Dictionary<string, string> headers = null)
{
using var resp = await GetAsync(url, headers);
resp.EnsureSuccessStatusCode();

var json = await resp.Content.ReadAsStringAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
}

public async Task<T> PostAsync<T>(string url, object data, Dictionary<string, string> headers = null)
{
using var resp = await PostAsync(url, data, headers);

resp.EnsureSuccessStatusCode();

var json = await resp.Content.ReadAsStringAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
}

public async Task<HttpResponseMessage> PostAsync(string url, object data, Dictionary<string, string> headers = null)
{
var httpclient = GetDefaultClient();
if (headers != null)
{
foreach (var header in headers)
{
httpclient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}

var jsondata = "";
if (data != null)
{
jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(data);
}
var stringContent = new StringContent(jsondata,
new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));

var resp = await httpclient.PostAsync(url, stringContent);

return resp;
}

public async Task<HttpResponseMessage> GetAsync(string url, Dictionary<string, string> headers = null)
{
var httpclient = GetDefaultClient();
if (headers != null)
{
foreach (var header in headers)
{
httpclient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
var resp = await httpclient.GetAsync(url);

return resp;
}
}
}
18 changes: 18 additions & 0 deletions src/AgileConfig.Server.Common/RestClient/IRestClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace AgileConfig.Server.Common.RestClient
{
public interface IRestClient
{
Task<T> GetAsync<T>(string url, Dictionary<string, string> headers = null);

Task<HttpResponseMessage> GetAsync(string url, Dictionary<string, string> headers = null);

Task<T> PostAsync<T>(string url, object data, Dictionary<string, string> headers = null);

Task<HttpResponseMessage> PostAsync(string url, object data, Dictionary<string, string> headers = null);

}
}
12 changes: 12 additions & 0 deletions src/AgileConfig.Server.Common/RestClient/ServiceCollectionEx.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Microsoft.Extensions.DependencyInjection;

namespace AgileConfig.Server.Common.RestClient
{
public static class ServiceCollectionEx
{
public static void AddRestClient(this IServiceCollection sc)
{
sc.AddScoped<IRestClient, DefaultRestClient>();
}
}
}
4 changes: 0 additions & 4 deletions src/AgileConfig.Server.IService/IRegisterCenterService.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
using AgileConfig.Server.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AgileConfig.Server.IService
Expand Down
10 changes: 7 additions & 3 deletions src/AgileConfig.Server.OIDC/OidcClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using AgileConfig.Server.OIDC.SettingProvider;
using AgileConfig.Server.Common;
using AgileConfig.Server.OIDC.SettingProvider;
using AgileConfig.Server.OIDC.TokenEndpointAuthMethods;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
Expand All @@ -10,11 +11,13 @@ public class OidcClient : IOidcClient
{
private readonly IOidcSettingProvider _oidcSettingProvider;
private readonly OidcSetting _oidcSetting;
private readonly IHttpClientFactory _httpClientFactory;

public OidcSetting OidcSetting => _oidcSetting;

public OidcClient(IOidcSettingProvider oidcSettingProvider)
public OidcClient(IOidcSettingProvider oidcSettingProvider, IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
_oidcSettingProvider = oidcSettingProvider;
_oidcSetting = _oidcSettingProvider.GetSetting();
}
Expand All @@ -35,7 +38,8 @@ public string GetAuthorizeUrl()
var authMethod = TokenEndpointAuthMethodFactory.Create(_oidcSetting.TokenEndpointAuthMethod);
var httpContent = authMethod.GetAuthHttpContent(code, _oidcSetting);

using var httpclient = new HttpClient();

var httpclient = _httpClientFactory.CreateClient(Global.DefaultHttpClientName);
if (!string.IsNullOrEmpty(httpContent.BasicAuthorizationString))
{
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", httpContent.BasicAuthorizationString);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AgileHttp" Version="0.0.6" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\AgileConfig.Server.Common\AgileConfig.Server.Common.csproj" />
<ProjectReference Include="..\AgileConfig.Server.Data.Freesql\AgileConfig.Server.Data.Freesql.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using AgileConfig.Server.IService;
using AgileConfig.Server.Common.RestClient;
using AgileConfig.Server.IService;
using Microsoft.Extensions.Logging;

namespace AgileConfig.Server.Service.EventRegisterService;
Expand All @@ -10,12 +11,12 @@ public class EventRegister : IEventRegister
private readonly SysLogRegister _sysLogRegister;
private readonly ServiceInfoStatusUpdateRegister _serviceInfoStatusUpdateRegister;

public EventRegister(IRemoteServerNodeProxy remoteServerNodeProxy, ILoggerFactory loggerFactory)
public EventRegister(IRemoteServerNodeProxy remoteServerNodeProxy, ILoggerFactory loggerFactory, IRestClient restClient)
{
_remoteServerNodeProxy = remoteServerNodeProxy;
_configStatusUpdateRegister = new ConfigStatusUpdateRegister(_remoteServerNodeProxy);
_sysLogRegister = new SysLogRegister();
_serviceInfoStatusUpdateRegister = new ServiceInfoStatusUpdateRegister(_remoteServerNodeProxy, loggerFactory);
_serviceInfoStatusUpdateRegister = new ServiceInfoStatusUpdateRegister(_remoteServerNodeProxy, loggerFactory, restClient);
}

public void Register()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Agile.Config.Protocol;
using AgileConfig.Server.Common;
using AgileConfig.Server.Common.RestClient;
using AgileConfig.Server.Data.Entity;
using AgileConfig.Server.Data.Freesql;
using AgileConfig.Server.IService;
using AgileHttp;
using Microsoft.Extensions.Logging;

namespace AgileConfig.Server.Service.EventRegisterService;

internal class ServiceInfoStatusUpdateRegister : IEventRegister
{
private readonly IRemoteServerNodeProxy _remoteServerNodeProxy;
private readonly IRestClient _restClient;
private ILogger _logger;

public ServiceInfoStatusUpdateRegister(IRemoteServerNodeProxy remoteServerNodeProxy, ILoggerFactory loggerFactory)
public ServiceInfoStatusUpdateRegister(
IRemoteServerNodeProxy remoteServerNodeProxy,
ILoggerFactory loggerFactory,
IRestClient restClient
)
{
_remoteServerNodeProxy = remoteServerNodeProxy;
_restClient = restClient;
_logger = loggerFactory.CreateLogger<ServiceInfoStatusUpdateRegister>();
}

Expand Down Expand Up @@ -129,14 +136,11 @@ private async Task SendServiceOfflineMessageAsync(ServiceInfo service)
{
await FunctionUtil.TRYAsync(async () =>
{
var resp = await service.AlarmUrl.AsHttp("POST", msg).Config(new RequestOptions()
{
ContentType = "application/json"
}).SendAsync();
if (resp.Exception != null)
{
throw resp.Exception;
}
var content = new StringContent("");
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
using var resp = await _restClient.PostAsync(service.AlarmUrl, null);
resp.EnsureSuccessStatusCode();
return resp.StatusCode == HttpStatusCode.OK;
}, 5);
Expand Down
Loading

0 comments on commit fe86291

Please sign in to comment.