【发布时间】:2021-10-29 00:21:56
【问题描述】:
我在 .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`
感谢任何帮助
【问题讨论】:
-
您可以阅读
InputStream,而不是阅读Body。请查看this answer。 -
对象 ActionExecutingContext 不包含 InputStream ActionExecutingContext.HttpContext.Request.InputStream 得到错误:HttpRequest'不包含'InputStream'的定义并且没有可访问的扩展方法'InputStream'@Peter Csala
-
HttpContext的类型是 HttpContextBase。它的Request的类型是HttpRequestBase。这个类确实有一个InputStream 属性。它们在System.Web中定义,而ActionExecutingContext在System.Web.Mvc中定义。 -
正如我所提到的,我在一个 ActionFilterAttribute 类中,我有一个 ActionExecutingContext 对象,其中包含使用 Microsoft.AspNetCore.Http @PeterCsala 下的 HttpRequest
-
对不起,you are right,我的错。
标签: c# .net-core actionfilterattribute