参考资料

https://www.cnblogs.com/wybin6412/p/10944077.html

.net core 3.0一个记录request和respose的中间件-LMLPHP

RequestResponseLog.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace LogRequestMiddleware
{
public class RequestResponseLog
{
public string Url { get; set; }
public IDictionary<string, string> Headers { get; set; } = new Dictionary<string, string>();
public string Method { get; set; }
public string RequestBody { get; set; }
public string ResponseBody { get; set; }
public DateTime ExcuteStartTime { get; set; }
public DateTime ExcuteEndTime { get; set; }
public override string ToString()
{
string headers = "[" + string.Join(",", this.Headers.Select(i => "{" + $"\"{i.Key}\":\"{i.Value}\"" + "}")) + "]";
return $"Url: {this.Url},\r\nHeaders: {headers},\r\nMethod: {this.Method},\r\nRequestBody: {this.RequestBody},\r\nResponseBody: {this.ResponseBody},\r\nExcuteStartTime: {this.ExcuteStartTime.ToString("yyyy-MM-dd HH:mm:ss.fff")},\r\nExcuteStartTime: {this.ExcuteEndTime.ToString("yyyy-MM-dd HH:mm:ss.fff")}";
}
}
}

RequestResponseLoggingMiddleware.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Internal;
using NLog; namespace LogRequestMiddleware
{
public class RequestResponseLoggingMiddleware
{
private readonly RequestDelegate _next;
private RequestResponseLog _logInfo; public RequestResponseLoggingMiddleware(RequestDelegate next)
{
_next = next;
} public async Task Invoke(HttpContext context)
{
_logInfo = new RequestResponseLog(); HttpRequest request = context.Request;
_logInfo.Url = request.Path.ToString();
_logInfo.Headers = request.Headers.ToDictionary(k => k.Key, v => string.Join(";", v.Value.ToList()));
_logInfo.Method = request.Method;
_logInfo.ExcuteStartTime = DateTime.Now; //获取request.Body内容
if (request.Method.ToLower().Equals("post"))
{ request.EnableBuffering(); //启用倒带功能,就可以让 Request.Body 可以再次读取 Stream stream = request.Body;
byte[] buffer = new byte[request.ContentLength.Value];
stream.Read(buffer, , buffer.Length);
_logInfo.RequestBody = Encoding.UTF8.GetString(buffer); request.Body.Position = ; }
else if (request.Method.ToLower().Equals("get"))
{
_logInfo.RequestBody = request.QueryString.Value;
} //获取Response.Body内容
var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream())
{
context.Response.Body = responseBody; await _next(context); _logInfo.ResponseBody = await FormatResponse(context.Response);
_logInfo.ExcuteEndTime = DateTime.Now;
Logger Logger = LogManager.GetCurrentClassLogger();
//log
Logger.Info($"VisitLog: {_logInfo.ToString()}");
//Logger.LogInfo(); await responseBody.CopyToAsync(originalBodyStream);
}
} private async Task<string> FormatResponse(HttpResponse response)
{
response.Body.Seek(, SeekOrigin.Begin);
var text = await new StreamReader(response.Body).ReadToEndAsync();
response.Body.Seek(, SeekOrigin.Begin); return text;
}
} public static class RequestResponseLoggingMiddlewareExtensions
{
public static IApplicationBuilder UseRequestResponseLogging(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestResponseLoggingMiddleware>();
}
}
}

sartup.cs

app.UseRequestResponseLogging();

一般来说,会遇到一个错误是包2.2的版本与.net core 3.0版本不一致

request.EnableRewind (); //这个方法无法使用 

你可以用这个request.EnableBuffering();

.net core 3.0一个记录request和respose的中间件-LMLPHP

VisitLog: Url: /weatherforecast,
Headers: [{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"},{"Accept-Encoding":"gzip, deflate, br"},{"Accept-Language":"zh,en-US;q=0.9,en;q=0.8"},{"Connection":"close"},{"Host":"localhost:44307"},{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36 Edg/80.0.361.53"},{"upgrade-insecure-requests":"1"},{"sec-fetch-dest":"document"},{"sec-fetch-site":"none"},{"sec-fetch-mode":"navigate"},{"sec-fetch-user":"?1"}],
Method: GET,
RequestBody: ?ID=9,
ResponseBody: [{"date":"2020-02-17T17:35:39.6927261+08:00","temperatureC":-9,"temperatureF":16,"summary":"Chilly"},{"date":"2020-02-18T17:35:39.6928616+08:00","temperatureC":22,"temperatureF":71,"summary":"Chilly"},{"date":"2020-02-19T17:35:39.6928634+08:00","temperatureC":34,"temperatureF":93,"summary":"Mild"},{"date":"2020-02-20T17:35:39.692864+08:00","temperatureC":28,"temperatureF":82,"summary":"Balmy"},{"date":"2020-02-21T17:35:39.6928647+08:00","temperatureC":-5,"temperatureF":24,"summary":"Freezing"}],
ExcuteStartTime: 2020-02-16 17:35:39.676,
ExcuteStartTime: 2020-02-16 17:35:39.708

05-25 23:51