. net core webapi: a method to obtain request and response content through Middleware

Time:2020-5-14

In this paper, middleware is used to implement the.net core webapiThe request and response data generated in are acquired and stored in the log file;

The use of log files is not covered in detail here. You can access NLog, log4net, exceptionless, etc

Middleware for creating interface records

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"));
      //Get request body content
      if (request.Method.ToLower().Equals("post"))
      {
        //With rewind enabled, you can Request.Body  Can be read again
        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);
      }
      //Get response.body content
      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);
      }
      //Response completion record time and log
      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>
    ///Get response content
    /// </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>
  ///Extended Middleware
  /// </summary>
  public static class RequestResponseLoggingMiddlewareExtensions
  {
    public static IApplicationBuilder UseRequestResponseLogging(this IApplicationBuilder app)
    {
      return app.UseMiddleware<RequestResponseLoggingMiddleware>();
    }
  }
}

Using middleware in the configure method in startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }
      app.UseErrorHandling (); // try to put global exceptions above
      ...
      app.UseRequestResponseLogging();
      ...
      app.UseExceptionless(Configuration);
      app.UseMvc();
    }

Now request to have a look at the effect of the record: my log exists on exceptionless, as shown below

Parse JSON and record the data as follows:

summary

The above is the method that Xiaobian introduced to you. Net core webapi obtains request and response content through middleware, hoping to help you. If you have any questions, please leave a message to me, and Xiaobian will reply you in time. Thank you very much for your support of the developepaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!