gpt4 book ai didi

c# - asp.net core i3.0 web api request.body 和 [frombody] 冲突

转载 作者:行者123 更新时间:2023-12-04 14:16:31 24 4
gpt4 key购买 nike

关闭。这个问题需要details or clarity .它目前不接受答案。












想改善这个问题吗?通过 editing this post 添加详细信息并澄清问题.

去年关闭。




Improve this question




我需要通过 request.body在 frombody 之后,但我测试了 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;
}

最佳答案

我相信您遇到的问题是您的 cccc空着回来。这可能是因为当您进入 Controller 时,请求正文流已经被读取。这是有道理的 - 有些东西必须填充 value参数给你。所以在这个阶段尝试倒带流已经太晚了。

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

启动文件

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);
}
}

最后在您的 Controller 中,您将从 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;
}

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

关于c# - asp.net core i3.0 web api request.body 和 [frombody] 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59598589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com