.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 ...
随机推荐
- 使用自定义注解和springAOP捕获Service层异常,并处理自定义异常
一 自定义异常 /** * 自定义参数为null异常 */ public class NoParamsException extends Exception { //用详细信息指定一个异常 publi ...
- 技术派-如果编译提示winnt.h(222):error C2146错误
如果编译的时候,出现如下错误: \Microsoft Studio 8\VC\PlatformSDK\include\winnt.h(222):error C2146: 语法错误:缺少“:”(在标识符 ...
- 05讲基础篇:某个应用的CPU使用率居然达到100%,我该怎么办
小结 CPU 使用率是最直观和最常用的系统性能指标,更是我们在排查性能问题时,通常会关注的第一个指标.所以我们更要熟悉它的含义,尤其要弄清楚用户(%user).Nice(%nice).系统(%syst ...
- Java学习笔记----打印基本数据类型范围
/** * Created by N3verL4nd on 2016/11/10. */ public class HelloWorld { public static void main(Strin ...
- mplayer使用心得[转]
一直在用mplayer,其他的播放器很少用.以下是我使用过程中的一些心得. 注意,下面用的路径都是在我的电脑上的路径,使用时请不要照抄!应该换成你的电脑上的正确路径. 一.首先还是讲安装方面的问题 ...
- ARTS Week 9
Dec 23, 2019 ~ Dec 29, 2019 Algorithm Problem 69 Sqrt(x) 实现求解平方根函数Sqrt(x) 题目链接 题目描述:给定一个非负数x,求解该数字的平 ...
- 初学maven的一些配置
初学Maven的一些配置 1.maven的安装 2.从官网下载3.6.1版本后,高级版本可能会出现不兼容 jdk1.8 3.配置maven 在 settings.xml <settings> ...
- 编辑crontab添加Linux计划任务
在做实验楼的比赛时的题目 用到了crontable 1. 为用户shiyanlou添加一个计划任务 2. 每天凌晨2点定时执行 3. 将/var/log/dpkg.log /var/log/mysql ...
- SpringProfile轻松切换多环境配置文件
在项目开发的过程中,我们难免会遇到开发.测试.生产等环境的切换,而各个环境的配置肯定是不同的.传统的办法是在项目打包的时候修改配置文件.但人为做的事情难免产生意外.Spring 为我们提供了一种多环境 ...
- pytorch之 CNN
# library # standard library import os # third-party library import torch import torch.nn as nn impo ...