-
-
Save kyrylomyr/17c4cb354c02b8badeecfe01580dc47b to your computer and use it in GitHub Desktop.
A code file from the blog article about dumping any request in ASP.NET Core 2.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
{ | |
services.AddRouting(); | |
} | |
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(); | |
app.UseRouter(routes); | |
} | |
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