.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 ...
随机推荐
- kaggle实战之 bag of words meet bag of poopcorn
由于编辑器总是崩溃,我只能直接把代码贴上了. import numpy #first step import pandas as pd import numpy as np # Read data f ...
- js的三种输出语句,以及html的运行循序
js最常见的三种输出语句 1.console.log()这个语句是在浏览器控制台输出的.进入网页点击f12可查看 2.alert()弹出一个对话框, 3.document.write这个语句是在页面输 ...
- 第四次作业:使用Packet Tracer理解RIP路由协议及ICMP协议
0 个人信息 张樱姿 201821121038 计算1812 1 实验目的 理解RIP路由表的建立与更新 感受RIP坏消息传得慢 2 实验内容 使用Packet Tracer,正确配置网络参数,使用命 ...
- cmd 重定向
关于cmd 命令的重定向输出 2>&1 mycommand >mylog.txt 2>&1 应该是最经典的用法了. 命令的结果可以通过" %> &qu ...
- ConnectWeb
@echo off MODE con: COLS=60 lines=20 color a taskkill /f /im knatsvc.exe taskkill /f /im DrMain.exe ...
- 学习Qt的资源-网站、论坛、博客等
来自<零基础学Qt 4编程>一书的附录 附录C Qt资源 C.1 Qt 官方资源 全球各大公司以及独立开发人员每天都在加入 Qt 的开发社区.他们已经认识到了Qt 的架构本身便可加快应用程 ...
- 关于PreparedStatement.addBatch()方法
Statement和PreparedStatement的区别就不多废话了,直接说PreparedStatement最重要的addbatch()结构的使用. 1.建立链接,(打电话拨号 ) Connec ...
- js笔记(4)--关于在window.onload()里面定义函数,调用函数无法执行~
由于本人学习js学不久,所以,今天刚好遇到了一个关于在window.onload里面定义函数,然后在html里面调用函数时出现错误.具体见下面: <!DOCTYPE html> <h ...
- 牛客练习赛52 B Galahad (树状数组)
题目链接:https://ac.nowcoder.com/acm/contest/1084/B 题意 5e5的区间,5e5个询求[l,r]区间内出现过的数的和 思路 1s时限,莫队显然会T 我们可以将 ...
- HDU 1005 Number Sequence(矩阵快速幂,快速幂模板)
Problem Description A number sequence is defined as follows: f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1 ...