c# - 在 OnActionExecuting 方法 dotnetCore 中获取请求正文
问题描述
我在 .net core3 中有 Web API。
在过滤器中,我需要获取请求正文
public override void OnActionExecuting(ActionExecutingContext context)
{
string body = ReadBodyAsString(context.HttpContext.Request);
}
private string ReadBodyAsString(HttpRequest request)
{
var initialBody = request.Body; // Workaround
try
{
request.EnableBuffering();
using (StreamReader reader = new StreamReader(request.Body))
{
string text = reader.ReadToEnd();
return text;
}
}
finally
{
// Workaround so MVC action will be able to read body as well
request.Body = initialBody;
}
return string.Empty;
}
我收到以下错误:
无法访问已释放的对象。\r\n对象名称: 'FileBufferingReadStream`
任何帮助表示赞赏
解决方案
StreamReader
有一个构造函数重载,它接受一个布尔值作为名为 的最终参数leaveOpen
。传入true
将阻止 the在其本身被处置时StreamReader
处置底层资产。Stream
确保...Body.Position
在完成读取后将属性设置为零以备将来读取(并且可能在您读取之前确保您从流的开头读取)。
推荐阅读
- php - Windows 10/Apache24/PHP 7.4.19 未加载 mysqli
- android-studio - java.lang.ClassCastException:无法投射 android.app.Application 使我的应用程序崩溃
- python - 熊猫数据帧索引中的2个条件
- flutter - 尝试将图像名称列表保存到 Firestore
- powerbi - Power BI 计算表未由数据切片器过滤
- python - 如何跨平台设置 Python 资源限制?
- shell - sed 替换引号中的字符串;带有反向引用;外壳脚本
- python - Python 和 BeautifulSoup4 - 如何调试发布请求响应?
- if-statement - 带有 IF 语句的 DAX 运行总日历日期问题
- mysql - 在 Doctrine 中管理两个具有不同自动增量的不同 id?