Я занимаюсь разработкой asp.net core 2.1 web api.в основном мне нужно было бы захватывать время запроса, URI запроса, тело запроса, время повторного ответа, тело ответа, код состояния, IP-адрес в серверной части асинхронно.Ниже образец я нашел его для Mvc Webapi.но не уверен, как использовать это в ядре asp.net 2.1.Любой рабочий образец будет высоко оценен.
https://www.infoworld.com/article/3211590/application-development/how-to-log-request-and-response-metadata-in-aspnet-web-api.html
public class CustomLogHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var logMetadata = BuildRequestMetadata(request);
var response = await base.SendAsync(request, cancellationToken);
logMetadata = BuildResponseMetadata(logMetadata, response);
await SendToLog(logMetadata);
return response;
}
private LogMetadata BuildRequestMetadata(HttpRequestMessage request)
{
LogMetadata log = new LogMetadata
{
RequestMethod = request.Method.Method,
RequestTimestamp = DateTime.Now,
RequestUri = request.RequestUri.ToString()
};
return log;
}
private LogMetadata BuildResponseMetadata(LogMetadata logMetadata, HttpResponseMessage response)
{
logMetadata.ResponseStatusCode = response.StatusCode;
logMetadata.ResponseTimestamp = DateTime.Now;
logMetadata.ResponseContentType = response.Content.Headers.ContentType.MediaType;
return logMetadata;
}
private async Task<bool> SendToLog(LogMetadata logMetadata)
{
// TODO: Write code here to store the logMetadata instance to a pre-configured log store...
return true;
}
}
public class LogMetadata
{
public string RequestContentType { get; set; }
public string RequestUri { get; set; }
public string RequestMethod { get; set; }
public DateTime? RequestTimestamp { get; set; }
public string ResponseContentType { get; set; }
public HttpStatusCode ResponseStatusCode { get; set; }
public DateTime? ResponseTimestamp { get; set; }
}