参考资料

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

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();

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

最新文章

  1. LeetCode#11. Container With Most Water
  2. offsetTop、clientTop、scrollTop、offsetTop
  3. [MySql] - 开启外部访问
  4. ini 文件操作记要(1): 使用 TIniFile
  5. 546C. Soldier and Cards
  6. c c++ 函数入口和出口的hook(gcc 编译选项),然后打印出函数调用关系的方法
  7. 设计模式(十一):FACADE外观模式 -- 结构型模式
  8. Oracle442个应用场景------------基础应用场景
  9. NSDictionary json格式字符串转字典,字典转json格式字符串
  10. linux popen函数
  11. LINUX下的远端主机登入 校园网络注册 网络数据包转发和捕获
  12. JavaScript语法详解:JS简介&amp;变量
  13. 从零开始学习前端开发 — 2、CSS基础
  14. Windows Sublime Text 配置Linux子系统(WSL)下的 gcc/g++ 编译环境
  15. ServerSocket详解及线程阻塞_03
  16. PMP项目管理考试培训机构内部资料打包赠送(3个PPT)
  17. 一种简单的ELF加固方法
  18. spirngcloud文件
  19. 【转】linux下各文件夹的结构说明及用途介绍
  20. MySQL学习笔记:少用Null

热门文章

  1. SpringBoot2.x整合JDBC及初始化data.sql和schema.sql脚本
  2. python 学习笔记2 匿名函数
  3. 每日一练PAT_B_PRAC_1005斐波那契凤尾
  4. Java 添加OLE对象到Excel文档
  5. python练习——第0题
  6. Go语言实现:【剑指offer】整数中1出现的次数(从1到n整数中1出现的次数)
  7. 《Head first设计模式》之观察者模式
  8. 面试题|手写JSON解析器
  9. 杭电-------2053Switch Game(C语言)
  10. 珠峰-node