.net core 3.0一个记录request和respose的中间件
参考资料
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
.net core 3.0一个记录request和respose的中间件的更多相关文章
- ASP.NET Core 1.0 开发记录
官方资料: https://github.com/dotnet/core https://docs.microsoft.com/en-us/aspnet/core https://docs.micro ...
- ASP.NET Core 5.0 中读取Request中Body信息
ASP.NET Core 5.0 中读取Request中Body信息 记录一下如何读取Request中Body信息 public class ValuesController : Controller ...
- ASP.NET Core 3.0 一个 jwt 的轻量角色/用户、单个API控制的授权认证库
目录 说明 一.定义角色.API.用户 二.添加自定义事件 三.注入授权服务和中间件 三.如何设置API的授权 四.添加登录颁发 Token 五.部分说明 六.验证 说明 ASP.NET Core 3 ...
- ASP.NET 5 RC1 升级 ASP.NET Core 1.0 RC2 记录
升级文档: Migrating from DNX to .NET Core Migrating from ASP.NET 5 RC1 to ASP.NET Core 1.0 RC2 Migrating ...
- ASP.NET Core 2.0 中读取 Request.Body 的正确姿势
原文:ASP.NET Core 中读取 Request.Body 的正确姿势 ASP.NET Core 中的 Request.Body 虽然是一个 Stream ,但它是一个与众不同的 Stream ...
- ASP.NET Core 1.0 静态文件、路由、自定义中间件、身份验证简介
概述 ASP.NET Core 1.0是ASP.NET的一个重要的重新设计. 例如,在ASP.NET Core中,使用Middleware编写请求管道. ASP.NET Core中间件对HttpCon ...
- .net core 2.0学习记录(一):搭建一个.Net Core网站项目
.Net Core开发可以使用Visual Studio 2017或者Visual Studio Code,下面使用Visual Studio 2017搭建一个.net Core MVC网站项目. 一 ...
- .net core 2.0学习记录(三):内置IOC与DI的使用
本篇的话介绍下IOC和ID的含义以及如何使用.Net Core中的DI. 一.我是这么理解IOC和DI的: IOC:没有用IOC之前是直接new实例来赋值,使用IOC之后是通过在运行的时候根据配置来实 ...
- .net core 2.0学习记录(四):Middleware使用以及模拟构建Middleware(RequestDelegate)管道
.net Core中没有继续沿用以前asp.net中的管道事件,而是开发了一个新的管道(Middleware): public class MiddlewareDemo { private reado ...
随机推荐
- 图像GIST特征和LMGIST包的python实现(有github)
1什么是Gist特征 (1) 一种宏观意义的场景特征描述 (2) 只识别"大街上有一些行人"这个场景,无需知道图像中在那些位置有多少人,或者有其他什么对 ...
- wordpress 如何防止盗链
盗链是指其它站点使用了你自己网站的图片音乐等资源,然后链接又没有更换,直接显示的就是你站点的图片,这在转载文章时最常见,比如转载时将 整篇文章都转载过去,包括文章里面的图片,有些人就懒得把图片再重新上 ...
- Codeforces_798
A.暴力把每个位置的字符改成另外25个字符,判断是否回文. #include<bits/stdc++.h> using namespace std; string s; int main( ...
- 《N诺机试指南》(二)C++自带实用函数
1.排序sort函数: 2.查找: 实例: 3. 队列:
- A simple way to monitor SQL server SQL performance.
This is all begins from a mail. ... Dear sir: This is liulei. Thanks for your help about last PM for ...
- 深入JVM垃圾回收机制,值得你收藏
JVM可以说是为了Java开发人员屏蔽了很多复杂性,让Java开发的变的更加简单,让开发人员更加关注业务而不必关心底层技术细节,这些复杂性包括内存管理,垃圾回收,跨平台等,今天我们主要看看JVM的垃圾 ...
- AppBox实战: 如何实现一对多表单的增删改查
本篇通过完整示例介绍如何实现一对多关系表单的相应服务及视图. 一.准备数据结构 示例所采用的数据结构为"物资需求"一对多"物资清单",通过IDE的实体设 ...
- C++ map通过key获取value
c++的map中通过key获取value的方法 一般是value =map[key],或者另一种迭代器的方式 1.在map中,由key查找value时,首先要判断map中是否包含key. 2.如果不 ...
- 《Head first设计模式》学习笔记
1. 单例模式 2. 工厂模式 3. 抽象工厂 4. 策略模式 5. 观察者模式 6. 装饰者模式 7. 命令模式 8. 适配器模式 9. 外观模式 10. 模版方法模式 11. 迭代器模式 设计模式 ...
- java程序设计原则知多少
程序设计七大原则 一.开闭原则 针对我们设计的功能模块对扩展开放,对修改关闭:利用面向接口(抽象)编程(多态的特性),实现对功能需求扩展的同时,不允许更改原来的代码.提高对象的可复用性.可维护性. ...