Consider the custom model binder below:
[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
});
}
}
Value of ms.Length
always equals to 0
.
Are there any ways to read request Body in a ModelBinder?
Also the below scenario seems weird to me:
public class TestController : Controller
{
[HttpPost]
public IActionResult Test(string data)
{
var ms = new MemoryStream();
request.Body.CopyTo(ms);
return OK(ms.Length);
}
}
It always returns 0
.
But when removing parameter string data
, it returns actual length of posted body.