我正在开发asp.net core 2.1 Web API。基本上,我将需要异步捕获后端中的请求时间,重发uri,requestbody,resepone时间,响应正文,状态码,ipaddress。下面的示例中,我发现它适用于mvc webapi。但不确定如何在asp.net core 2.1中使用它。任何工作样品都会受到高度赞赏。
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; }
}