Dumping any requests in ASP.NET Core 2.0
Once, I was needed to have a simple endpoint in which I can send any request for test purposes. Just a simple web service that eats a request, no matter what HTTP method and route are used.
Fortunately, Microsoft did a great job making ASP.NET Core as flexible as possible, so the solution turned up quite short and simple.
All that we need is to create an empty ASP.NET Core 2.0 Web Application in Visual Studio. Some backbone will be generated. First, add the Routing in the service configuration:
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
}
It allows us to configure what routes we will handle.
The next step is to define our own handler:
var routeHandler = new RouteHandler(
context =>
{
var path = Dump(context);
// Write the response to the user.
return context.Response.WriteAsync($"Saved to '{path}'.");
});
Method Dump()
just saves the request body into a text file which name consists of the HTTP method, route, and date-time of the request. We also write the raw response to the user so he can see that the web service actually works.
The last step is to register our handler. Its can be done using the RouteBuilder
:
var routeBuilder = new RouteBuilder(app, routeHandler);
routeBuilder.MapRoute("Dump Any Request", "{*.}");
var routes = routeBuilder.Build();
app.UseRouter(routes);
I hope, someone will find this small application useful. Additional details of how to dump the actual request, get the route, and the whole application you can find on GitHub.