3

我需要request.body在frombody之后让body通过,但是测试了2天还没有找到解决办法。我已经添加了Request.EnableBuffering().

// PUT: api/Test/5
[HttpPut("{id}")]
public async Task<string> PutAsync(int id, [FromBody]ProductInfo value)
{
    var ccccc = "";
    Request.EnableBuffering();
    using (var reader = new StreamReader(Request.Body, encoding: System.Text.Encoding.UTF8))
    {
        var body = await reader.ReadToEndAsync();
        ccccc = body;
        Request.Body.Position = 0;
    }
    return ccccc;
}
4

1 回答 1

3

我相信你遇到的问题是你cccc空空如也。这可能是因为当您进入控制器时,请求正文流已经被读取。这是有道理的 - 必须value为您填充参数。所以在这个阶段尝试倒带已经太迟了。

ASP.NET 博客有一篇关于如何处理此问题的文章:您需要一个自定义中间件,并且需要将其插入到 MVC 中间件上方的管道中。

启动.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<CustomMiddleware>(); // register your custom middleware with DI container
    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMiddleware<CustomMiddleware>(); // inject your middleware before MVC injects theirs

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

那么您的自定义中间件可能如下所示:

自定义中间件.cs

public class CustomMiddleware : IMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        context.Request.EnableBuffering(); // now you can do it

        // Leave the body open so the next middleware can read it.
        using (var reader = new StreamReader(context.Request.Body, encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true))
        {
            var body = await reader.ReadToEndAsync();
            context.Items.Add("body", body); // there are ways to pass data from middleware to controllers downstream. this is one. see https://stackoverflow.com/questions/46601757/c-sharp-dotnet-core-2-pass-data-from-middleware-filter-to-controller-method for more

            // Reset the request body stream position so the next middleware can read it
            context.Request.Body.Position = 0;
        }

        // Call the next delegate/middleware in the pipeline
        await next(context);
    }
}

最后在你的控制器中,你会像这样获取身体context

// PUT: api/Test/5
[HttpPut("{id}")]
public async Task<string> PutAsync(int id, [FromBody]ProductInfo value)
{            
    var ccccc = (string)HttpContext.Items["body"];
    return ccccc;
}

这种方法有一些注意事项,在文章中进行了讨论。注意巨大的请求体并相应地调整缓冲区大小。

于 2020-01-06T02:22:49.310 回答