溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

.net core webapi如何通過中間件獲取請求和響應(yīng)內(nèi)容

發(fā)布時間:2021-05-22 10:52:06 來源:億速云 閱讀:522 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹了.net core webapi如何通過中間件獲取請求和響應(yīng)內(nèi)容,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

本文主要根據(jù)中間件來實現(xiàn)對.net core webapi中產(chǎn)生的請求和響應(yīng)數(shù)據(jù)進(jìn)行獲取并存入日志文件中;

這里不詳細(xì)介紹日志文件的使用。你可以自己接入NLog,log4net,Exceptionless等

創(chuàng)建接口記錄的中間件

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內(nèi)容
      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內(nèi)容
      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);
      }
      // 響應(yīng)完成記錄時間和存入日志
      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>
    /// 獲取響應(yīng)內(nèi)容
    /// </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>
  /// 擴(kuò)展中間件
  /// </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();
    }

現(xiàn)在請求一次看一下記錄的效果:我的日志存在exceptionless上,如下圖

.net core webapi如何通過中間件獲取請求和響應(yīng)內(nèi)容

 解析json,記錄的數(shù)據(jù)如下:

.net core webapi如何通過中間件獲取請求和響應(yīng)內(nèi)容

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“.net core webapi如何通過中間件獲取請求和響應(yīng)內(nèi)容”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI