🍓 refactor(HttpRemote): 远程请求配置优化
This commit is contained in:
parent
0c4dd289d3
commit
d492a46a14
@ -36,12 +36,14 @@ public static class HttpRemotesExtension {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 设置Http远程服务选项
|
/// 携带接口描述相关属性
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static HttpRequestBuilder SetHttpOptions(this HttpRequestBuilder builder, HttpRemoteItem option, string apiDesc = "")
|
/// <param name="builder"></param>
|
||||||
|
/// <param name="httpName"></param>
|
||||||
|
/// <param name="desc"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static HttpRequestBuilder SetRemoteApiAttr(this HttpRequestBuilder builder, string httpName, string desc = "")
|
||||||
{
|
{
|
||||||
builder.SetHttpClientName(option.HttpName);
|
return HttpLoggingHandler.SetRemoteApiAttr(builder, httpName, desc);
|
||||||
builder.WithHeader(CommonConst.HttpRemoteApiDescHeaderName, apiDesc, replace:true);
|
|
||||||
return builder;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -38,6 +38,7 @@ public class HttpLoggingHandler : DelegatingHandler, ITransient
|
|||||||
if (!string.IsNullOrWhiteSpace(clientName)) enabledLog = _enabledLogMap.GetOrDefault(clientName);
|
if (!string.IsNullOrWhiteSpace(clientName)) enabledLog = _enabledLogMap.GetOrDefault(clientName);
|
||||||
if (!enabledLog) return await base.SendAsync(request, cancellationToken);
|
if (!enabledLog) return await base.SendAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
var stopWatch = Stopwatch.StartNew();
|
||||||
var sysLogHttp = new SysLogHttp();
|
var sysLogHttp = new SysLogHttp();
|
||||||
sysLogHttp.HttpClientName = clientName;
|
sysLogHttp.HttpClientName = clientName;
|
||||||
|
|
||||||
@ -48,20 +49,17 @@ public class HttpLoggingHandler : DelegatingHandler, ITransient
|
|||||||
sysLogHttp.HttpMethod = request.Method.Method;
|
sysLogHttp.HttpMethod = request.Method.Method;
|
||||||
sysLogHttp.RequestUrl = request.RequestUri?.ToString();
|
sysLogHttp.RequestUrl = request.RequestUri?.ToString();
|
||||||
sysLogHttp.RequestHeaders = request.Headers.ToDictionary(u => u.Key, u => u.Value.Join(";")).ToJson();
|
sysLogHttp.RequestHeaders = request.Headers.ToDictionary(u => u.Key, u => u.Value.Join(";")).ToJson();
|
||||||
|
|
||||||
if (request.Content != null) sysLogHttp.RequestBody = await request.Content.ReadAsStringAsync(cancellationToken);
|
if (request.Content != null) sysLogHttp.RequestBody = await request.Content.ReadAsStringAsync(cancellationToken);
|
||||||
|
|
||||||
sysLogHttp.StartTime = DateTime.Now;
|
sysLogHttp.StartTime = DateTime.Now;
|
||||||
var stopWatch = Stopwatch.StartNew();
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var response = await base.SendAsync(request, cancellationToken);
|
var response = await base.SendAsync(request, cancellationToken);
|
||||||
stopWatch.Stop();
|
stopWatch.Stop();
|
||||||
sysLogHttp.EndTime = DateTime.Now;
|
sysLogHttp.EndTime = DateTime.Now;
|
||||||
|
sysLogHttp.StatusCode = response.StatusCode;
|
||||||
sysLogHttp.ResponseHeaders = response.Headers.ToDictionary(u => u.Key, u => u.Value.Join(";")).ToJson();
|
sysLogHttp.ResponseHeaders = response.Headers.ToDictionary(u => u.Key, u => u.Value.Join(";")).ToJson();
|
||||||
sysLogHttp.IsSuccessStatusCode = response.IsSuccessStatusCode ? YesNoEnum.Y : YesNoEnum.N;
|
sysLogHttp.IsSuccessStatusCode = response.IsSuccessStatusCode ? YesNoEnum.Y : YesNoEnum.N;
|
||||||
sysLogHttp.StatusCode = response.StatusCode;
|
|
||||||
|
|
||||||
sysLogHttp.ResponseBody = await response.Content.ReadAsStringAsync(cancellationToken);
|
sysLogHttp.ResponseBody = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
@ -79,4 +77,18 @@ public class HttpLoggingHandler : DelegatingHandler, ITransient
|
|||||||
await _eventPublisher.PublishAsync(nameof(AppEventSubscriber.CreateHttpLog), sysLogHttp, cancellationToken);
|
await _eventPublisher.PublishAsync(nameof(AppEventSubscriber.CreateHttpLog), sysLogHttp, cancellationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置接口描述相关属性
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="builder"></param>
|
||||||
|
/// <param name="httpName"></param>
|
||||||
|
/// <param name="desc"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static HttpRequestBuilder SetRemoteApiAttr(HttpRequestBuilder builder, string httpName, string desc = "")
|
||||||
|
{
|
||||||
|
builder.WithHeader(CommonConst.HttpRemoteApiDescHeaderName, desc, replace:true);
|
||||||
|
builder.SetHttpClientName(httpName);
|
||||||
|
return builder;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@ -24,6 +24,22 @@ public class WorkWxBaseService(
|
|||||||
IHttpRemoteService httpRemoteService,
|
IHttpRemoteService httpRemoteService,
|
||||||
IOptions<HttpRemotesOptions> options) : ITransient
|
IOptions<HttpRemotesOptions> options) : ITransient
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 获取企业微信接口凭证
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> GetTokenAsync()
|
||||||
|
{
|
||||||
|
using var disposable = sysCacheService.BeginCacheLock(WorkWeixinConst.KeyLockWorkWeixin);
|
||||||
|
var result = await SendAsync<TokenWorkWxInput, TokenWorkWxOutput>(new()
|
||||||
|
{
|
||||||
|
CorpId = await sysConfigService.GetConfigValueByCode(WorkWeixinConst.WorkWeixinCorpId),
|
||||||
|
CorpSecret = await sysConfigService.GetConfigValueByCode(WorkWeixinConst.WorkWeixinCorpSecret)
|
||||||
|
});
|
||||||
|
sysCacheService.Set(WorkWeixinConst.KeyWorkWeixinToken, result.AccessToken, TimeSpan.FromSeconds(result.ExpiresIn));
|
||||||
|
return result.AccessToken;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 发起请求
|
/// 发起请求
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -33,12 +49,13 @@ public class WorkWxBaseService(
|
|||||||
/// <returns>返回结果</returns>
|
/// <returns>返回结果</returns>
|
||||||
public async Task<R> SendAsync<T, R>(T input) where R : BaseWorkWxOutput
|
public async Task<R> SendAsync<T, R>(T input) where R : BaseWorkWxOutput
|
||||||
{
|
{
|
||||||
|
var opt = options.Value.WorkWeixin;
|
||||||
var attr = typeof(T).GetCustomAttribute<HttpRemoteApiAttribute>();
|
var attr = typeof(T).GetCustomAttribute<HttpRemoteApiAttribute>();
|
||||||
if (attr == null || string.IsNullOrWhiteSpace(attr.Action) || string.IsNullOrWhiteSpace(attr.Desc))
|
if (attr == null || string.IsNullOrWhiteSpace(attr.Action) || string.IsNullOrWhiteSpace(attr.Desc))
|
||||||
throw Oops.Oh($"接口入参类型({typeof(T).FullName})未正确配置[HttpRemoteApi]特性");
|
throw Oops.Oh($"接口入参类型({typeof(T).FullName})未正确配置[HttpRemoteApi]特性");
|
||||||
|
|
||||||
// 拼接请求地址,并设置token
|
// 拼接请求地址,并设置token
|
||||||
var url = options.Value.WorkWeixin.BaseAddress + $"/cgi-bin/{attr.Action}?";
|
var url = opt.BaseAddress + $"/cgi-bin/{attr.Action}?";
|
||||||
if (input is AuthWorkWxInput)
|
if (input is AuthWorkWxInput)
|
||||||
{
|
{
|
||||||
var token = sysCacheService.Get<string>(WorkWeixinConst.KeyWorkWeixinToken) ?? await GetTokenAsync();
|
var token = sysCacheService.Get<string>(WorkWeixinConst.KeyWorkWeixinToken) ?? await GetTokenAsync();
|
||||||
@ -52,9 +69,9 @@ public class WorkWxBaseService(
|
|||||||
{
|
{
|
||||||
HttpMethodEnum.Get => await httpRemoteService.GetAsync(
|
HttpMethodEnum.Get => await httpRemoteService.GetAsync(
|
||||||
url + input.ToCustomJsonPropertyQueryString(),
|
url + input.ToCustomJsonPropertyQueryString(),
|
||||||
builder => builder.SetHttpOptions(options.Value.WorkWeixin, attr.Desc)),
|
builder => builder.SetRemoteApiAttr(opt.HttpName, attr.Desc)),
|
||||||
HttpMethodEnum.Post => await httpRemoteService.PostAsync(url,
|
HttpMethodEnum.Post => await httpRemoteService.PostAsync(url,
|
||||||
builder => builder.SetHttpOptions(options.Value.WorkWeixin, attr.Desc)
|
builder => builder.SetRemoteApiAttr(opt.HttpName, attr.Desc)
|
||||||
.SetContent(new StringContent(JSON.Serialize(input, CustomJsonPropertyConverter.Options), Encoding.UTF8, "application/json"))),
|
.SetContent(new StringContent(JSON.Serialize(input, CustomJsonPropertyConverter.Options), Encoding.UTF8, "application/json"))),
|
||||||
_ => throw Oops.Oh($"[企业微信] 不支持的请求方式{attr.HttpMethod.ToString()}:({typeof(T).FullName})"),
|
_ => throw Oops.Oh($"[企业微信] 不支持的请求方式{attr.HttpMethod.ToString()}:({typeof(T).FullName})"),
|
||||||
};
|
};
|
||||||
@ -84,7 +101,7 @@ public class WorkWxBaseService(
|
|||||||
{
|
{
|
||||||
var resp = JSON.Deserialize<R>(responseContent, CustomJsonPropertyConverter.Options);
|
var resp = JSON.Deserialize<R>(responseContent, CustomJsonPropertyConverter.Options);
|
||||||
if (resp?.ErrCode == 0) return resp;
|
if (resp?.ErrCode == 0) return resp;
|
||||||
throw Oops.Oh("[企业微信] 请求失败:" + resp?.ErrMsg);
|
throw Oops.Oh("[企业微信] " + resp?.ErrMsg);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@ -92,20 +109,4 @@ public class WorkWxBaseService(
|
|||||||
throw Oops.Oh((ex is AppFriendlyException ? "" : "[企业微信] 序列化失败:") + ex.Message);
|
throw Oops.Oh((ex is AppFriendlyException ? "" : "[企业微信] 序列化失败:") + ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 获取企业微信接口凭证
|
|
||||||
/// </summary>
|
|
||||||
/// <returns></returns>
|
|
||||||
private async Task<string> GetTokenAsync()
|
|
||||||
{
|
|
||||||
using var disposable = sysCacheService.BeginCacheLock(WorkWeixinConst.KeyLockWorkWeixin);
|
|
||||||
var result = await SendAsync<TokenWorkWxInput, TokenWorkWxOutput>(new()
|
|
||||||
{
|
|
||||||
CorpId = await sysConfigService.GetConfigValueByCode(WorkWeixinConst.WorkWeixinCorpId),
|
|
||||||
CorpSecret = await sysConfigService.GetConfigValueByCode(WorkWeixinConst.WorkWeixinCorpSecret)
|
|
||||||
});
|
|
||||||
sysCacheService.Set(WorkWeixinConst.KeyWorkWeixinToken, result.AccessToken, TimeSpan.FromSeconds(result.ExpiresIn));
|
|
||||||
return result.AccessToken;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Loading…
Reference in New Issue
Block a user