Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A code file from the blog article about dumping any request in ASP.NET Core 2.0
using System;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace RequestDump
public class Startup
public void ConfigureServices(IServiceCollection services)
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
var routeHandler = new RouteHandler(
context =>
var path = Dump(context);
// Write the response to the user so he can see that request was dumped.
return context.Response.WriteAsync($"Request saved to '{path}'.");
var routeBuilder = new RouteBuilder(app, routeHandler);
routeBuilder.MapRoute("Dump Any Request", "{*.}");
var routes = routeBuilder.Build();
private static string Dump(HttpContext context)
var httpMethod = context.Request.Method;
// Get the full route of the request to use it as a part of dump file.
var route = context.GetRouteData().Values["."];
// Create file name.
var fileName = EscapeInvalidChars($"{httpMethod}_{DateTime.Now:yyMMdd_HHmmss}_{route}.txt");
var path = Path.Combine(@"C:\Dump", fileName);
using (var reader = new StreamReader(context.Request.Body))
// Read the full body of the request and save it to file.
var body = reader.ReadToEnd();
File.WriteAllText(path, body);
return path;
private static string EscapeInvalidChars(string invalidFileName, char escapeChar = '_')
var builder = new StringBuilder(invalidFileName);
var invalidChars = Path.GetInvalidFileNameChars().Concat(Path.GetInvalidPathChars());
foreach (var c in invalidChars)
builder.Replace(c, escapeChar);
return builder.ToString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.