受欢迎的博客标签

Source Code view source code Introduction

In this blog I will create a middleware to log the request and response of an API.

Middleware is a piece of code, a class in this example that sets in the request/response pipeline to do specific things. Our middleware will log the request and response that goes in and out of an API call respectively. Logging Mechanism To keep thing simple and focused, I am using the built in Logger that is shipped with ASP.NET core. This logger logs information to the console in this example as information.

Log Request Middleware The log request middleware extracts the request body and convert it to a string. It also logs the request url which will include any query string parameters if they exist.

Here is the definition for this middleware.

step 1.create a .NET Core library project

To start, create a .NET Core library (the project type is under web templates and is called classlibrary(.NetCore).

 

step 2. reference ASP.NET Core  in .NET Core library project

To reference ASP.NET Core, add the following <FrameworkReference> element to your project file:

iAspNetCore.Middleware\src\Middleware\iAspNetcore.Middleware.LogRequest\iAspNetcore.Middleware.LogRequest.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

  <ItemGroup>

    <PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.1" />
  </ItemGroup>

</Project>

 

step 3.Middleware class

iAspNetCore.Middleware\src\Middleware\iAspNetcore.Middleware.LogRequest\LogRequestMiddleware.cs

namespace iAspNetcore.Middleware.LogRequest
{

    /// <summary>
    /// 
    /// </summary>
    public class LogRequestMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger<LogRequestMiddleware> _logger;
        private Func<string, Exception, string> _defaultFormatter = (state, exception) => state;

        public LogRequestMiddleware(RequestDelegate next, ILogger<LogRequestMiddleware> logger)
        {
            this.next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            var url = UriHelper.GetDisplayUrl(context.Request);

            // _logger.LogInformation($"\n{DateTime.Now.ToString()}-Request url: {url},\nRequest Method: {context.Request.Method},Request Schem: {context.Request.Scheme}, UserAgent: {context.Request.Headers[HeaderNames.UserAgent].ToString()}");

            string requestUrlString = $"Request url: {url},Request Method: {context.Request.Method},Request Schem: {context.Request.Scheme}, UserAgent: {context.Request.Headers[HeaderNames.UserAgent].ToString()}";

            string allkeypair = "";
            IHeaderDictionary headers = context.Request.Headers;

            foreach (var headerValuePair in headers)
            {
                allkeypair += "\n" + headerValuePair.Key + ":" + headerValuePair.Value;

            }

            string requestHeadersString = $"Request.Headers:\n {allkeypair.ToString()}";

            // this._logger.LogInformation($"\n{DateTime.Now.ToString()}Request.Headers:{0}\n" + allkeypair.ToString());




            var requestBodyStream = new MemoryStream();
            var originalRequestBody = context.Request.Body;

            await context.Request.Body.CopyToAsync(requestBodyStream);
            requestBodyStream.Seek(0, SeekOrigin.Begin);


            var requestBodyText = new StreamReader(requestBodyStream).ReadToEnd();
            //    _logger.LogInformation($"\n{DateTime.Now.ToString()}-Request Body: {requestBodyText}");

            var requestBodyString = $"Request Body: {requestBodyText}";

            requestBodyStream.Seek(0, SeekOrigin.Begin);
            context.Request.Body = requestBodyStream;

            _logger.LogInformation($"{DateTime.Now.ToString()}-{requestUrlString}\n{requestHeadersString}\n{requestBodyString}");

            await next(context);
            context.Request.Body = originalRequestBody;
        }
    }

 

step 4.Middleware extension method

iAspNetCore.Middleware\src\Middleware\iAspNetcore.Middleware.LogRequest\LogRequestMiddlewareExtensions.cs

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.AspNetCore.Builder;




namespace iAspNetcore.Middleware.LogRequest
{

    public static class LogRequestMiddlewareExtensions
    {
        public static IApplicationBuilder UseiAspNetcoreLogRequest(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<LogRequestMiddleware>();
        }
    }
}

 

step 5.calls the middleware 

reference LogRequestMiddleware .NET Core library project

iAspNetCore.Middleware\src\Samples\TestSamples\TestSamples.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <ProjectReference Include="..\..\Middleware\iAspNetcore.Middleware.LogRequest\iAspNetcore.Middleware.LogRequest.csproj" />
    <ProjectReference Include="..\..\Middleware\iAspNetcore.Middleware.LogResponse\iAspNetcore.Middleware.LogResponse.csproj" />
  </ItemGroup>



</Project>

 

he following code calls the middleware from Startup.Configure:

iAspNetCore.Middleware\src\Samples\TestSamples\Startup.cs

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
           ...

            app.UseiAspNetcoreLogRequest();
            app.UseiAspNetcoreLogResponse();

            ..
        }

 

demo:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: G:\CommonWebApi\iAspNetCore.Middleware\src\Samples\TestSamples
info: iAspNetcore.Middleware.LogRequest.LogRequestMiddleware[0]
      2020/1/31 6:03:03-Request url: http://localhost:5000/,Request Method: GET,Request Schem: http, UserAgent: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0
Request.Headers:
 
Cache-Control:max-age=0
Connection:keep-alive
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.5
Cookie:Hm_lvt_e18fbcb7d76bcfdeb044be28749e9e18=1580226621; Nop.customer=836e1dab-62a4-4b0f-8b61-7c5ef91a7634
Host:localhost:5000
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0
Upgrade-Insecure-Requests:1
Request Body: 
info: iAspNetcore.Middleware.LogResponse.LogResponseMiddleware[0]
      
2020/1/31 6:03:03-Request url: http://localhost:5000/,
Request Method: GET,Request Schem: http, UserAgent: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0
info: iAspNetcore.Middleware.LogResponse.LogResponseMiddleware[0]
      
2020/1/31 6:03:03Response.Headers:0

 

 

github:https://github.com/iaspnetcore/iAspNetCore.Middleware