C# 在自定义ModelBinder中使用Request.Body
请考虑以下自定义模型绑定器:C# 在自定义ModelBinder中使用Request.Body,c#,asp.net-core,asp.net-core-2.0,asp.net-core-mvc-2.0,C#,Asp.net Core,Asp.net Core 2.0,Asp.net Core Mvc 2.0,请考虑以下自定义模型绑定器: [ModelBinder(typeof(CustomModelBinder))] public class StreamModel { public MemoryStream Stream { get; set; } } public class CustomModelBinder : IModelBinder { public async Task BindModelAsync(ModelBindi
[ModelBinder(typeof(CustomModelBinder))]
public class StreamModel
{
public MemoryStream Stream
{
get;
set;
}
}
public class CustomModelBinder : IModelBinder
{
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
var request = bindingContext.HttpContext.Request;
var ms = new MemoryStream();
request.Body.CopyTo(ms);
bindingContext.Result = ModelBindingResult.Success(new StreamModel
{
Stream = ms
});
}
}
ms.Length
的值始终等于0
。
有没有办法读取ModelBinder中的请求正文
另外,我觉得下面的场景很奇怪:
public class TestController : Controller
{
[HttpPost]
public IActionResult Test(string data)
{
var ms = new MemoryStream();
request.Body.CopyTo(ms);
return OK(ms.Length);
}
}
它总是返回0
。
但是,当删除参数
字符串数据时,它会返回已发布正文的实际长度。问题是您试图多次读取请求正文
有关解决方法和更多信息,请查看以下问题:
使用app.Use(next=>context=>{context.Request.EnableRewind();返回next(context);})代码>有效,但我没有多次阅读request.Body。(我认为mvc在内部做到了这一点)。(将在github上的mvc回购中为此创建一个问题)可能重复