我正在使用this从输入流中获取请求参数。 POST在请求正文中使用JSON。在我的onAuthorize
函数中,它覆盖了AuthorizeAttribute
。它确实给了我请求体参数,但是它会清空流,因此控制器不会收到任何请求参数:
public override void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.HttpContext.Request.InputStream.Length() //17 here
string jsonPostData;
using (var stream = filterContext.HttpContext.Request.InputStream)
{
stream.Position = 0;
using (var reader = new System.IO.StreamReader(stream))
{
jsonPostData = reader.ReadToEnd();
}
}
filterContext.HttpContext.InputStream.Length() //0 here
filterContext.HttpContext.Request.InputStream.Position = 0; // still 0
base.OnAuthorization(filterContext); //so when the request reaches controller its empty
}
我想我基本上要问的是如何在读取后重置输入流
答案 0 :(得分:0)
阅读完流后,您可以在开头重置其位置:
stream.Position = 0;
在开始阅读流之前你已经这样做了,所以在阅读之后尝试以相同的方式重置它。
答案 1 :(得分:0)
将代码更改为此内容并开始工作
public override void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.HttpContext.Request.InputStream.Length() //17 here
string jsonPostData;
var stream = request.InputStream;
var reader = new System.IO.StreamReader(stream);
jsonPostData = reader.ReadToEnd();
filterContext.HttpContext.InputStream.Length() //17 here
filterContext.HttpContext.Request.InputStream.Position = 0; //17 here
base.OnAuthorization(filterContext); //so when the request reaches controller its empty
}