I'm creating a public REST Api using ASP.NET Core 1.0 RC2 and like to log incoming requests and outgoing responses.
I have created a middleware class which is added to the pipeline before the call to app.UseMvc();
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseIOMiddleware();
app.UseMvc();
}
My Middleware class looks like this:
public class IOMiddleware
{
private readonly RequestDelegate _next;
public IOMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
LogRequest(context.Request);
await _next.Invoke(context);
}
private async void LogRequest(HttpRequest request)
{
using (var bodyReader = new StreamReader(request.Body))
{
string body = await bodyReader.ReadToEndAsync();
request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
System.Diagnostics.Debug.Print(body);
}
}
}
I can read the request body stream and rewind it using this example: Rewind request body stream, but I'm not sure how to read the response body as the stream is not readable.
In Web API 2.0 I could have used the HttpResponseMessage.Content.ReadAsByteArrayAsync() method, but how can I accomplish the same thing in ASP.Net Core 1.0 RC2?