本文主要根据中间件来实现对.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通过中间件获取请求和响应内容的更多相关文章

  1. 第十九节:Asp.Net Core WebApi基础总结和请求方式

    一. 基础总结 1.Restful服务改造 Core下的WebApi默认也是Restful格式服务,即通过请求方式(Get,post,put,delete)来区分请求哪个方法,请求的URL中不需要写方 ...

  2. NetCore 中间件获取请求报文和返回报文

    using System; using System.IO; namespace WebApi.Restful.Middlewares { public class MemoryWrappedHttp ...

  3. .net core MVC 通过 Filters 过滤器拦截请求及响应内容

    前提: 需要nuget   Microsoft.Extensions.Logging.Log4Net.AspNetCore   2.2.6: Swashbuckle.AspNetCore 我暂时用的是 ...

  4. C#使用WebClient时,如果状态码不为200时,如何获取请求返回的内容

    目录 一.事故现场 二.解决方法 一.事故现场 使用WebClient发送请求,如果返回的状态码不是2xx或3xx,那么默认情况下会抛出异常, 那如何才能获取到请求返回的内容呢? 二.解决方法 可以通 ...

  5. Servlet-2获取请求,响应结果

    获取请求参数值1)HttpServletRequest ①      该接口是ServletRequest接口的子接口,封装了HTTP请求的相关信息,由Servlet容器创建其实现类对象并传入serv ...

  6. 3-Fiddler修改请求或响应内容

    1.修改请求内容 方法一:设置请求前断点,修改请求后发送 1)设置断点 2)选中请求,在inspectors下修改请求内容 3)修改请求后,点击Break on Response按钮,进行请求的发送 ...

  7. .Net Core WebApi控制器接收原始请求正文内容

    主要目标 在Asp.net Core控制器中,通过自定义格式化程序来映射自定义处理控制器中的“未知”内容. 简单案例 为了演示这个问题,我们用VS2017创建一个默认的Asp.net Core Web ...

  8. Asp.Net WebAPI 通过HttpContextBase获取请求参数

    WEBAPI中的Request是HttpRequestMessage类型,不能像Web传统那样有querystring和from 方法接收参数,而传统的HttpReqest的基类是HttpReqest ...

  9. django中间件(获取请求ip)

    def simple_middleware(get_response): # 此处编写的代码仅在Django第一次配置和初始化的时候执行一次. print('1----django启动了') def ...

随机推荐

  1. xcode7: Undefined symbols for architecture i386: "_iconv_open", referenced from:

    在整合cocos和quick时,出现这个错误,我按照以前的方法 link binary with libraries 中add libiconv.2.dylib ,发现已经没有了这个库. 网上找了一下 ...

  2. Johnson算法:多源最短路算法

    Johnson算法 请不要轻易点击标题 一个可以在有负边的图上使用的多源最短路算法 时间复杂度\(O(n \cdot m \cdot log \ m+n \cdot m)\) 空间复杂度\(O(n+m ...

  3. 联想M7216NWA墨粉清零:

    在设备就绪状态下,按"功能"键,进入设置菜单,按上下键进行选择,屏幕出现"设备信息"项时按"确认"键,再按上下键选择,当屏幕出现" ...

  4. [Web Pdf] flying-saucer + iText + Freemarker生成pdf 跨页问题

    转载于: https://blog.csdn.net/qq_31980421/article/details/79662988 flying-saucer + iText +  Freemarker实 ...

  5. 【C++】C++中explicity关键字的使用

    读者可以尝试预言一下这段代码的输出: #include <iostream> using namespace std; class Complex { private: double re ...

  6. LeetCode 110. Balanced Binary Tree(判断平衡二叉树)

    Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary ...

  7. TCP报文结构

    来自:https://blog.csdn.net/qq_32998153/article/details/79680704

  8. 大数据 -- Hadoop集群环境搭建

    首先我们来认识一下HDFS, HDFS(Hadoop Distributed File System )Hadoop分布式文件系统.它其实是将一个大文件分成若干块保存在不同服务器的多个节点中.通过联网 ...

  9. Centos7环境下部署搭建discuz论坛

    1.首先搭建lnmp环境 2.从官网复制git地址(https://gitee.com/ComsenzDiscuz/DiscuzX),在服务器上安装git命令 yum install git -y  ...

  10. 升级go mod采坑录

    为了使用go mod把golang升级到了最新的1.12版本,go mod是1.11版本引入的,go mod的引入极大的方便了golang项目的依赖管理,同时把golang项目从GOPATH中解放了出 ...