在IActionFilter OnActionExecuting()中获取请求的大小

问题描述 投票:0回答:1

项目设置:Asp .NET core 2.1,Docker环境下的Web Api。

我想在我们的API上获取带有查询参数的GET请求的大小,以进行记录。我在项目中有一个实现IActionFilter的动作过滤器。 OnActionExecuting()是我为此目的解释请求的方法。

但是我总是在context.HttpContext.Request.ContentLength属性中获取null。另外,通过流阅读器在文本变量(也为空)中读取正文。这是一个有效的检查位置,还是我指的是ActionExecutingContext的不同属性?

public void OnActionExecuting(ActionExecutingContext context)
{

string requestSize = "";

//Try 1:
requestSize = Convert.ToString(context.HttpContext.Request.ContentLength);

//Try 2:
//Since the Try 1 is null, following doesn't really matter. But still tried.
using (var bodyReader = new StreamReader(context.HttpContext.Request.Body))
{
     var bodyAsText = bodyReader.ReadToEnd();
     if (string.IsNullOrWhiteSpace(bodyAsText) == false)
     {
     requestSize = bodyAsText.Length;
     }
}

// Console.WriteLine(requestSize );

}

期望一些字节数用于请求大小,但会为空。

c# request asp.net-core-2.1
1个回答
0
投票

这是检查此的有效地点

NO

GET请求没有身体。

ContentLength为null且空的主体流是GET请求的预期行为。

如果要访问查询字符串,则需要检查请求URL并提取查询字符串

© www.soinside.com 2019 - 2024. All rights reserved.