本文主要根据中间件来实现对.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. Tecplot显示周期和对称算例

    源视频链接:https://pan.baidu.com/s/1HdU3nsti8qLZhXvISxsSFA 提取码: 3kfu 模型链接:https://pan.baidu.com/s/1CQCGL7 ...

  2. 转载:关于思科交换机、路由器如何关闭telnet 开启ssh服务

    等保测评要求: 必须关闭telnet服务,开启ssh服务 即用ssh方式登录网络设备,而不允许用telnet. 输入密码.en 再次输入密码.sh run 这些常规动作就不再赘述. 1.关闭telne ...

  3. Server Tomcat v8.5 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.

    Server Tomcat v9.0 Server at localhost was unable to start within 45 seconds. If the server requires ...

  4. Springboot 条件注解

    @Conditional 根据满足某一个特定条件创建一个特定的 Bean.就是根据特定条件来控制 Bean 的创建行为,这样我们可以利用这个特性进行一些自动的配置 Springboot 中大量用到了条 ...

  5. 列表初始化 分析initializer_list<T>的实现

    列表初始化(1)_统一初始化 1. 统一初始化(Uniform Initialization) (1)在C++11之前,很多程序员特别是初学者对如何初始化一个变量或对象的问题很容易出现困惑.因为可以用 ...

  6. LeetCode 104. Maximum Depth of Binary Tree(二叉树深度)

    Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the long ...

  7. Manytasking optimization MATP

    Manytasking Jmetal代码反向解析1_MATP测试函数集 觉得有用的话,欢迎一起讨论相互学习~Follow Me 这是我在写Manytask optimization时的笔记,代码地址可 ...

  8. Superset配置impala数据源

    1.安装impyla pip install impyla 2.在superset页面配置如下,此时impala是有kerberos认证的 impala://xxxx:xx/default?auth_ ...

  9. linux安装jira

    JIRA配置本地MYSQL数据库 https://blog.csdn.net/coin_one/article/details/78376238 jira7.3.6 linux安装及破解 https: ...

  10. 【视频开发】Gstreamer框架中使用gst-launch进行流媒体播放

    Gstreamer框架中使用gst-launch进行流媒体播放 Gstreamer是一套开源的流媒体框架,用其也可以进行流媒体开发,Gstreamer是基于glib库编写的,需要将多个不同功能的元件( ...