首页 技术 正文
技术 2022年11月19日
0 收藏 671 点赞 3,045 浏览 1360 个字

ASP.NET Core 中的 Request.Body 虽然是一个 Stream ,但它是一个与众不同的 Stream —— 不允许 Request.Body.Position=0 ,这就意味着只能读取一次,要想多次读取,需要借助 MemoryStream ,详见博问 asp.net core中2次读取Request.Body的问题

using (var buffer = new MemoryStream())
{
Request.Body.CopyTo(buffer);
buffer.Position = ;
buffer.CopyTo(writer.BaseStream);
Console.WriteLine("Request.Body:");
buffer.Position = ;
buffer.CopyTo(Console.OpenStandardOutput());
}

昨天读了博文 Reading request body in ASP.NET Core 之后得知在 ASP.NET Core 2.0 中已经针对这个问题提供了解决方法 —— EnableRewind() ,只要启用倒带功能,就可以让  Request.Body 回归正常 Stream 。

使用非常简单,引用命名空间 Microsoft.AspNetCore.Http.Internal ,调用方法 Request.EnableRewind()  即可,下面我们用简单的示例代码体验一下

public class HomeController : Controller
{
public IActionResult Index()
{
Request.EnableRewind(); Console.WriteLine("Request.Body1:");
Request.Body.Position = ;
Request.Body.CopyTo(Console.OpenStandardOutput());
Console.WriteLine(); Console.WriteLine("Request.Body2:");
Request.Body.Position = ;
Request.Body.CopyTo(Console.OpenStandardOutput());
Console.WriteLine(); return Ok();
}
}

启动上面的 ASP.NET Core 站点,然后用 curl 命令发出请求

curl -X POST -d 'Hello World' localhost:5000

控制台就会输出期望的结果

Request.Body1:
Hello World
Request.Body2:
Hello World

EnableRewind 有 2 个参数 bufferThreshold 与 bufferLimit 。 bufferThreshold 设置的是 Request.Body 最大缓存字节数(默认是30K),超出这个阈值的字节会被写入磁盘;bufferLimit 设置的是 Request.Body 允许的最大字节数(默认值是null),超出这个限制,就会抛出异常  System.IO.IOException 。

EnableRewind 的实现源代码见 BufferingHelper.cs

更新:.NET Core 3.0 中 EnableRewind 被改名为 EnableBuffering 。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,999
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,357
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,140
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848