【发布时间】:2016-10-17 17:54:26
【问题描述】:
我正在使用 ASP.NET Core 1.0 RC2 创建一个公共 REST Api,并且喜欢记录传入请求和传出响应。
我创建了一个中间件类,它在调用 app.UseMvc();之前添加到管道中;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseIOMiddleware();
app.UseMvc();
}
我的中间件类如下所示:
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);
}
}
}
我可以使用以下示例读取请求正文流并将其倒回:Rewind request body stream,但由于流不可读,我不确定如何读取响应正文。
在 Web API 2.0 中,我可以使用 HttpResponseMessage.Content.ReadAsByteArrayAsync() 方法,但如何在 ASP.Net Core 1.0 RC2 中完成同样的事情?
【问题讨论】:
-
这能回答你的问题吗? How to read ASP.NET Core Response.Body?
标签: c# asp.net-core-1.0