Search code examples
c#asp.net-coreasp.net-core-2.0asp.net-core-mvc-2.0

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.


Solution

  • 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