我正在重新实现一个请求记录器作为 Owin 中间件,它记录所有传入请求的请求 url 和正文。我能够读取正文,但如果我这样做,我的控制器中的正文参数为空。
我猜它是空的,因为流位置在末尾,所以当它试图反序列化主体时,没有什么可读取的了。我在以前版本的 Web API 中遇到了类似的问题,但能够将 Stream 位置设置回 0。这个特定的流会引发This stream does not support seek operations异常。
在最新版本的 Web API 2.0 中,我可以Request.HttpContent.ReadAsStringAsync()在我的请求记录器中调用,并且主体仍会完整地到达控制器。
阅读后如何回退流?
或者
如何在不使用请求正文的情况下读取它?
public class RequestLoggerMiddleware : OwinMiddleware
{
public RequestLoggerMiddleware(OwinMiddleware next)
: base(next)
{
}
public override Task Invoke(IOwinContext context)
{
return Task.Run(() => {
string body = new StreamReader(context.Request.Body).ReadToEnd();
// log body
context.Request.Body.Position = 0; // cannot set stream position back to 0
Console.WriteLine(context.Request.Body.CanSeek); // prints false
this.Next.Invoke(context);
});
}
}
public class SampleController : ApiController
{
public void Post(ModelClass body)
{
// body is now null if the middleware reads it
}
}