.net core webapi通过中间件获取请求和响应内容
本文主要根据中间件来实现对.net core webapi中产生的请求和响应数据进行获取并存入日志文件中;
这里不详细介绍日志文件的使用。你可以自己接入NLog,log4net,Exceptionless等
创建接口记录的中间件
using Microliu.Core.Loggers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Ptibro.Partner.API.Extensions
{ public class RequestResponseLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger; private SortedDictionary<string, object> _data;
private Stopwatch _stopwatch; public RequestResponseLoggingMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
_stopwatch = new Stopwatch();
} public async Task Invoke(HttpContext context)
{
_stopwatch.Restart();
_data = new SortedDictionary<string, object>(); HttpRequest request = context.Request;
_data.Add("request.url", request.Path.ToString());
_data.Add("request.headers", request.Headers.ToDictionary(x => x.Key, v => string.Join(";", v.Value.ToList())));
_data.Add("request.method", request.Method);
_data.Add("request.executeStartTime", DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); // 获取请求body内容
if (request.Method.ToLower().Equals("post"))
{
// 启用倒带功能,就可以让 Request.Body 可以再次读取
request.EnableRewind(); Stream stream = request.Body;
byte[] buffer = new byte[request.ContentLength.Value];
stream.Read(buffer, , buffer.Length);
_data.Add("request.body", Encoding.UTF8.GetString(buffer)); request.Body.Position = ;
}
else if (request.Method.ToLower().Equals("get"))
{
_data.Add("request.body", request.QueryString.Value);
} // 获取Response.Body内容
var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream())
{
context.Response.Body = responseBody; await _next(context); _data.Add("response.body", await GetResponse(context.Response));
_data.Add("response.executeEndTime", DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); await responseBody.CopyToAsync(originalBodyStream);
} // 响应完成记录时间和存入日志
context.Response.OnCompleted(() =>
{
_stopwatch.Stop();
_data.Add("elaspedTime", _stopwatch.ElapsedMilliseconds + "ms");
var json = JsonConvert.SerializeObject(_data);
_logger.Debug(json, "api", request.Method.ToUpper());
return Task.CompletedTask;
}); } /// <summary>
/// 获取响应内容
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public async Task<string> GetResponse(HttpResponse response)
{
response.Body.Seek(, SeekOrigin.Begin);
var text = await new StreamReader(response.Body).ReadToEndAsync();
response.Body.Seek(, SeekOrigin.Begin);
return text;
}
} /// <summary>
/// 扩展中间件
/// </summary>
public static class RequestResponseLoggingMiddlewareExtensions
{
public static IApplicationBuilder UseRequestResponseLogging(this IApplicationBuilder app)
{
return app.UseMiddleware<RequestResponseLoggingMiddleware>();
}
} }
在startup.cs中Configure方法中使用中间件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseErrorHandling();// 全局异常尽量放上面
...
app.UseRequestResponseLogging();
...
app.UseExceptionless(Configuration);
app.UseMvc();
}
现在请求一次看一下记录的效果:我的日志存在exceptionless上,如下图
解析json,记录的数据如下:
参考地址:https://www.cnblogs.com/wybin6412/p/10944077.html (我只是在此基础上进行了一些小的改善)
.net core webapi通过中间件获取请求和响应内容的更多相关文章
- 第十九节:Asp.Net Core WebApi基础总结和请求方式
一. 基础总结 1.Restful服务改造 Core下的WebApi默认也是Restful格式服务,即通过请求方式(Get,post,put,delete)来区分请求哪个方法,请求的URL中不需要写方 ...
- NetCore 中间件获取请求报文和返回报文
using System; using System.IO; namespace WebApi.Restful.Middlewares { public class MemoryWrappedHttp ...
- .net core MVC 通过 Filters 过滤器拦截请求及响应内容
前提: 需要nuget Microsoft.Extensions.Logging.Log4Net.AspNetCore 2.2.6: Swashbuckle.AspNetCore 我暂时用的是 ...
- C#使用WebClient时,如果状态码不为200时,如何获取请求返回的内容
目录 一.事故现场 二.解决方法 一.事故现场 使用WebClient发送请求,如果返回的状态码不是2xx或3xx,那么默认情况下会抛出异常, 那如何才能获取到请求返回的内容呢? 二.解决方法 可以通 ...
- Servlet-2获取请求,响应结果
获取请求参数值1)HttpServletRequest ① 该接口是ServletRequest接口的子接口,封装了HTTP请求的相关信息,由Servlet容器创建其实现类对象并传入serv ...
- 3-Fiddler修改请求或响应内容
1.修改请求内容 方法一:设置请求前断点,修改请求后发送 1)设置断点 2)选中请求,在inspectors下修改请求内容 3)修改请求后,点击Break on Response按钮,进行请求的发送 ...
- .Net Core WebApi控制器接收原始请求正文内容
主要目标 在Asp.net Core控制器中,通过自定义格式化程序来映射自定义处理控制器中的“未知”内容. 简单案例 为了演示这个问题,我们用VS2017创建一个默认的Asp.net Core Web ...
- Asp.Net WebAPI 通过HttpContextBase获取请求参数
WEBAPI中的Request是HttpRequestMessage类型,不能像Web传统那样有querystring和from 方法接收参数,而传统的HttpReqest的基类是HttpReqest ...
- django中间件(获取请求ip)
def simple_middleware(get_response): # 此处编写的代码仅在Django第一次配置和初始化的时候执行一次. print('1----django启动了') def ...
随机推荐
- xargs 命令教程
转自阮一峰 http://www.ruanyifeng.com/blog/2019/08/xargs-tutorial.html 仅供个人交流学习 xargs是 Unix 系统的一个很有用的命令,但是 ...
- 干货收藏 | Java 程序员必备的一些流程图
阅读本文大概需要 6 分钟. 转载自:https://juejin.im/post/5d214639e51d4550bf1ae8df 1.Spring 的生命周期 Spring 作为当前 Java 最 ...
- select多选左移右移的实现
<html> <head> <meta http-equiv="Content-Type" content="text/html; char ...
- create-react-app项目暴露webpack配置文件
create-react-app创建的react项目,webapck配置,默认情况下是在node_modules里面的,我们需要把它暴露到根目录上来. 执行 npm run eject 命令即可,一般 ...
- TX-LCN5.0.2分布式事务框架源码分析-关键线索罗列-txc部分
1.注解TxcTransaction2.在其注解接口附近查找aop配置:TransactionAspect3.runTransaction是在执行事务业务代码时的包装逻辑4.transactionSe ...
- Python知乎上推荐的项目
原文地址:https://www.zhihu.com/question/29372574/answer/88744491 作者:Wayne Shi链接:https://www.zhihu.com/qu ...
- Sword 位运算取余操作
/* 位运算取余操作 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include ...
- kerberos相关
1.kerberos认证覆盖问题 先显示指定KRB5CCNAME存储的路径 export KRB5CCNAME=/tmp/krb5cc_xxx kinit -kt /home/xxx.keytab x ...
- 开源录屏软件Capture推荐
参考链接:有哪些值得推荐的电脑录屏软件与手机录屏软件? - 霸都丶傲天的回答 - 知乎 下载地址(9.0支持中文)
- Oracle 实现表中id字段自增长
Oracle 实现表中id字段自增长 最近正在学习Oracle的时候发现Oracle表中的字段不能像mysql中那样可以用auto increment修饰字段从而让id这种主键字段实现自增长. 那Or ...