我相信我可以与httpclient消息处理程序一起使用服务器端消息处理程序,因为它们实际上是相同的,但我只是想确定一下,因为我不确定100%。
当前,我正在使用Web API编写休息服务,任务之一是
我必须记录请求和每个请求的响应。
这些服务还在内部调用另一个服务,以获取一些我正在使用HTTP Client的数据。在这里我也需要登录 请求/响应。
我的消息处理程序看起来像这样
public class ApiLoggingHandler : DelegatingHandler
{
private readonly CustomLogType customLogType;
public ApiLoggingHandler(HttpMessageHandler innerHandler, CustomLogType customLogType)
: base(innerHandler)
{
}
public ApiLoggingHandler(CustomLogType customLogType)
{
this.customLogType = customLogType;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var logger = CustomLogFactory.Create(customLogType);
Tuple<string,string> controllerActionNames = GetControllerActionName(request);
Dictionary<string, string> requestHeaders = request.Headers?.ToDictionary(a => a.Key, a => string.Join(";", a.Value));
await LogRequestAsync(request,request.RequestUri?.PathAndQuery, controllerActionNames.Item1, controllerActionNames.Item2, requestHeaders, logger);
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Dictionary<string, string> responseHeaders = response.Headers?.ToDictionary(a => a.Key, a => string.Join(";", a.Value));
await LogResponseAsync(response, request.RequestUri?.PathAndQuery, controllerActionNames.Item1, controllerActionNames.Item2, responseHeaders, logger);
return response;
}
这是我们在global.ascx上注册的消息处理程序
config.MessageHandlers.Add(new ApiLoggingHandler(CustomLogType.LOG4NET));
我的httpclient是静态的,并重复使用与
相同的消息处理程序public class WebRequestHandler
{
private static HttpClient client;
static WebRequestHandler()
{
client = new HttpClient(new ApiLoggingHandler(new HttpClientHandler(),CustomLogType.LOG4NET));
}
public async Task<TResult> GetAsync<TResult>(string requesturl, string authToken)
{
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requesturl);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (!string.IsNullOrEmpty(authToken)) request.Headers.Add("Authorization", authToken);
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAync<TResult>();
}
catch (HttpRequestException e)
{
throw e;
}
}
}
请说明我在做什么,并且秤不会造成任何问题。