Capturing full request in DotNet Core API

In this tutorial we will show code how to capture full request to web api in dotnet core





Code

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace LogFullRequestResponse
{
    public class RequestLoggingMiddleware
    {   
        private readonly RequestDelegate _next;
        public RequestLoggingMiddleware(RequestDelegate next)
        {
            _next = next;          
        }
        public async Task Invoke(HttpContext context)
        {
            var injectedRequestStream = new MemoryStream();
            try
            {
                var requestLog = $"REQUEST HttpMethod: {context.Request.Method},
 Path: {context.Request.Path}";
                using (var bodyReader = new StreamReader(context.Request.Body))
                {
                    var bodyAsText = bodyReader.ReadToEnd();
                    if (string.IsNullOrWhiteSpace(bodyAsText) == false)
                    {
                        requestLog += $", Body : {bodyAsText}";
                    }
                    var bytesToWrite = Encoding.UTF8.GetBytes(bodyAsText);
                    injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
                    injectedRequestStream.Seek(0, SeekOrigin.Begin);
                    context.Request.Body = injectedRequestStream;
                }
                Logger.Instance.WriteLog("Invoke", "requestLog:" + requestLog);
                await _next.Invoke(context);                                
            }
            finally
            {
                injectedRequestStream.Dispose();
            }
        }       
    }
}

In Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            // Enable middleware to serve generated Swagger as a JSON endpoint.           
            app.UseMiddleware();
            app.UseMvc();
            app.UseStaticFiles();
        }
Reactions

Post a Comment

0 Comments