在自定义AuthorizeAttribute中获取Post请求参数
我用它来从输入流中获取请求参数。 POST在请求正文中使用JSON。 在我的onAuthorize
函数中,它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 }
我想我本质上要问的是如何在读取后重置输入流
读完流后,您可以在开头重置其位置:
stream.Position = 0;
您在开始阅读流之前已经这样做了,所以在阅读之后尝试以相同的方式重置它。
将代码更改为此并开始工作
上述就是C#学习教程:在自定义AuthorizeAttribute中获取Post请求参数分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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 }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/956967.html