【问题标题】:ASP.NET Core 3.1 reading Request body empty stringASP.NET Core 3.1 读取请求正文空字符串
【发布时间】:2021-07-09 18:23:25
【问题描述】:

所以我有这个:

app.Use(async (context, next) =>
            {
                context.Request.EnableBuffering();
                await next();
            });

还有这个:

private async Task<JObject> GetRequestBodyAsync(HttpRequest request)
{
        JObject objRequestBody = new JObject();

        try
        {
            // IMPORTANT: Leave the body open so the next middleware can read it.
            using (StreamReader reader = new StreamReader(
                request.Body,
                Encoding.UTF8,
                detectEncodingFromByteOrderMarks: false,
                leaveOpen: true))
            {
                string strRequestBody = await reader.ReadToEndAsync();
                objRequestBody = JsonConvert.DeserializeObject<JObject>(strRequestBody);
            }
        }
        finally
        {
            // IMPORTANT: Reset the request body stream position so the next middleware can read it
            request.Body.Position = 0;
        }

        return objRequestBody;
}

但是虽然request.Body.Length &gt; 0(如预期的那样),这行:

string strRequestBody = await reader.ReadToEndAsync();

总是返回一个空字符串。有什么想法吗?

接下来的操作检索[FromBody] OK。

【问题讨论】:

    标签: asp.net-core-3.1


    【解决方案1】:

    从 .NET Core 2.2 升级到 3.1 后,我在应用程序中遇到了同样的问题并找到了解决方案。

    在 startup.cs 中,您的代码必须位于管道的开头:`

    public void Configure(IApplicationBuilder app)
    {
        app.Use((context, next) =>
        {
            context.Request.EnableBuffering();
            return next();
        });
    
    
        // ...More configurations go here
    }
    

    之后,您可以在代码中使用它:

        private async Task<JObject> GetRequestBodyAsync(HttpRequest request)
        {
            JObject objRequestBody = new JObject();
    
            try
            {
                // set the pointer to the beninig of the stream in case it already been readed
                request.Body.Position = 0; 
                using (StreamReader reader = new StreamReader(request.Body)
                {
                    string strRequestBody = await reader.ReadToEndAsync();
                    objRequestBody = JsonConvert.DeserializeObject<JObject>(strRequestBody);
                }
            }
            finally
            {
                request.Body.Position = 0;
            }
    
            return objRequestBody;
    }
    

    欲了解更多信息:https://justsimplycode.com/2020/08/02/reading-httpcontext-request-body-content-returning-empty-after-upgrading-to-net-core-3-from-2-0/

    【讨论】:

      猜你喜欢
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多