简体   繁体   English

来自.Net Core 3.0的请求正文为空

[英]Request body from is empty in .Net Core 3.0

Okay so I've been wracking my brain and cannot for the life of me understand why the exact same piece of code works perfectly in.Net Core 2.2 but returns an empty string in.Net Core 3.0.好的,所以我一直在绞尽脑汁,无法理解为什么完全相同的代码在.Net Core 2.2 中完美运行,但在.Net Core 3.0 中返回一个空字符串。

The piece of code I am running is this:我正在运行的代码是这样的:

public static async Task<string> GetRequestBodyAsync(this HttpRequest request,
                                                     Encoding encoding = null)
{
    if (encoding == null) encoding = Encoding.UTF8;
    var body = "";

    request.EnableBuffering();
    if (request.ContentLength == null || !(request.ContentLength > 0) || !request.Body.CanSeek) return body;

    request.Body.Seek(0, SeekOrigin.Begin);
    using (var reader = new StreamReader(request.Body, encoding, true, 1024, true))
        body = await reader.ReadToEndAsync();

    request.Body.Position = 0;
    return body;
}

And I call this extension as such:我这样称呼这个扩展:

var bodyContent = await Request.GetRequestBodyAsync();
var body = new MemoryStream(Encoding.UTF8.GetBytes(bodyContent));

In.Net Core 2.2 I get the body of the sent payload exactly as I want it, but in.Net Core 3.0 I get an empty string.在.Net Core 2.2 中,我得到了我想要的已发送有效负载的主体,但在.Net Core 3.0 中,我得到了一个空字符串。

I am using the extension in my startup to add Newtonsoft to my project for.Net Core 3.0, but if I remove that it still doesn't work.我在我的启动中使用扩展程序将 Newtonsoft 添加到我的.Net Core 3.0 项目中,但如果我删除它仍然无法工作。

Any ideas what I might've done wrong?任何想法我可能做错了什么?

Add this middleware in the startup class:在启动类中添加这个中间件:

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

I actually figured it out, in the controller-method I read the body using [FromBody] so that the body was being read twice and not rewinded the first time.我实际上想通了,在控制器方法中,我使用[FromBody]读取正文,以便正文被读取两次而不是第一次倒带。

public async Task<ActionResult<string>> PaymentRequestCallbackAsync(/*[FromBody] SecretModel model*/)
{
    var body = await Request.GetRequestBodyAsync();
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(body));
    return body;
}

So remove the [FromBody] and it should work just fine.所以删除[FromBody] ,它应该可以正常工作。

Here is another solution which will help这是另一个有帮助的解决方案

write a middleware写一个中间件

public class EnableRequestBodyBufferingMiddleware
        {
            private readonly RequestDelegate _next;

            public EnableRequestBodyBufferingMiddleware(RequestDelegate next) =>
                _next = next;

            public async Task InvokeAsync(HttpContext context)
            {
                context.Request.EnableBuffering();

                await _next(context);
            }
        }

Then configure this middleware然后配置这个中间件

app.UseMiddleware<EnableRequestBodyBufferingMiddleware>();

Now you can easily ready the body without any problem现在您可以轻松准备好身体,没有任何问题

        Request.EnableBuffering();
        Request.Body.Seek(0, SeekOrigin.Begin);
        using (StreamReader stream = new StreamReader(Request.Body))
        {
            string body = await stream.ReadToEndAsync();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET MVC Core 3.0 - 为什么 API 来自正文的请求不断返回。ModelState?IsValid? - ASP.NET MVC Core 3.0 - Why API Request from body keeps returning !ModelState.IsValid? 从视图到 controller 的 Ajax 请求正文在 ASP NET Core MVC 3 中为空 - Ajax request body from view to controller is empty in ASP NET Core MVC 3 C#Net Core API Post JSON请求正文为空 - C# net core api post json request body is empty .net 核心在获取请求时返回空主体 json - .net core returns empty body json on Get request 为什么添加请求参数时我的 Request.BodyReader 为空(ASP.NET Core 3.0) - Why my Request.BodyReader is empty when i add request parameters (ASP.NET Core 3.0) ASP.NET Core从ActionExecutedContext ActionFilter获取请求正文 - ASP.NET Core Get Request Body from ActionExecutedContext ActionFilter 如何使 .NET 4.8 中的 Request.Content 在.Net Core 中工作? 或者 Request.Body 从.Net Core 到 .NET 4.8? - How to make Request.Content from .NET 4.8 to work in .Net Core? Or Request.Body from .Net Core to .NET 4.8? ASP.NET 核心异步请求处理程序总是以 200 OK 和空主体响应,如果它是一个单独的方法 - ASP.NET Core async request handler always responds with 200 OK and empty body if it's a separate method 在 ASP.Net Core 3.0 中多次读取正文 - Read Body multiple times in ASP.Net Core 3.0 从NET Core 3.0中的代码获取ApplicationIcon - Get ApplicationIcon from Code in NET Core 3.0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM