考虑下面的自定义模型绑定器:
[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中读取请求Body?
以下情况对我来说似乎很奇怪:
public class TestController : Controller
{
[HttpPost]
public IActionResult Test(string data)
{
var ms = new MemoryStream();
request.Body.CopyTo(ms);
return OK(ms.Length);
}
}
它始终返回0
。
但是当删除参数string data
时,它会返回已发布实体的实际长度。