.net core webapi通过中间件获取请求和响应内容的方法

所属分类: 网络编程 / ASP.NET 阅读数: 1657
收藏 0 赞 0 分享

本文主要根据中间件来实现对.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, 0, buffer.Length);
        _data.Add("request.body", Encoding.UTF8.GetString(buffer));
        request.Body.Position = 0;
      }
      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(0, SeekOrigin.Begin);
      var text = await new StreamReader(response.Body).ReadToEndAsync();
      response.Body.Seek(0, 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,记录的数据如下:

以上所述是小编给大家介绍的.net core webapi通过中间件获取请求和响应内容的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

更多精彩内容其他人还在看

解析WPF实现音频文件循环顺序播放的解决方法

本篇文章是对WPF实现音频文件循环顺序播放的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解决.net framework 4.0环境下遇到版本不同编译不通过的方法详解

本篇文章是对.net framework 4.0环境下遇到版本不同编译不通过的解决方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

将文件上传、下载(以二进制流保存到数据库)实现代码

将文件以二进制流的格式写入数据库:首先获得文件路径,然后将文件以二进制读出保存在一个二进制数组中具体请祥看本文,希望对你有所帮助
收藏 0 赞 0 分享

点击提交按钮后DropDownList的值变为默认值实现分析

在点击提交按钮后,页面上所有的绑定到数据库的控件值都恢复到默认值,下面与大家分享下DropDownList的值变为默认值
收藏 0 赞 0 分享

ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法

ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

Linkbutton控件在项目中的简单应用

Button控件可分为button控件、LinkButton控件、ImageButton控件三类,而LinkButton控件则在页面上显示为一个超级链接,下面与大家分享下其具体应用
收藏 0 赞 0 分享

Web.config 和 App.config 的区别分析

Web.config 和 App.config 的区别分析,需要的朋友可以参考一下
收藏 0 赞 0 分享

基于.Net中的数字与日期格式化规则助记词的使用详解

本篇文章是对.Net中的数字与日期格式化规则助记词的使用进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解决在Web.config或App.config中添加自定义配置的方法详解

本篇文章是对在Web.config或App.config中添加自定义配置的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入本机影像生成器(Ngen.exe)工具使用方法详解

本篇文章是对本机影像生成器(Ngen.exe)工具使用方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享
查看更多