Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Request.Body in custom ModelBinder

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.

like image 944
Ashkan Nourzadeh Avatar asked Nov 28 '25 18:11

Ashkan Nourzadeh


1 Answers

The problem is you are trying to read the request body multiple times.

For a workaround and more information, you should take a look at this question: Read request body twice

like image 132
ctyar Avatar answered Nov 30 '25 09:11

ctyar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!