Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected end of Stream, the content may have already been read by another component. Microsoft.AspNetCore.WebUtilities.MultipartReaderStream

I get an exception when I try to read multi part content from the request saying the content may have already been read by another component.

 if (MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                // Used to accumulate all the form url encoded key value pairs in the 
                // request.
                var formAccumulator = new KeyValueAccumulator();

                var boundary = Request.GetMultipartBoundary();
                var reader = new MultipartReader(boundary, HttpContext.Request.Body);
                var section = await reader.ReadNextSectionAsync();
                while (section != null)
                {
                    ContentDispositionHeaderValue contentDisposition;
                    var hasContentDispositionHeader =
                        ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
                }
            }
like image 934
Sunil Buddala Avatar asked Apr 16 '18 22:04

Sunil Buddala


2 Answers

In asp.net core 3, You have to add factories.RemoveType<FormFileValueProviderFactory>(); to your DisableFormValueModelBindingAttribute attribute.

Code

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DisableFormValueModelBindingAttribute : Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        var factories = context.ValueProviderFactories;
        factories.RemoveType<FormValueProviderFactory>();
        factories.RemoveType<FormFileValueProviderFactory>();
        factories.RemoveType<JQueryFormValueProviderFactory>();
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }
}

Documentation

like image 53
Learner Avatar answered Nov 12 '22 07:11

Learner


It turns out that I had to disable form value model binding by using the attribute below.

[HttpPost]
    [Route("")]
    [DisableFormValueModelBinding]
    public async Task<IActionResult> Post()

The attribute implementation is below

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DisableFormValueModelBindingAttribute : Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        var factories = context.ValueProviderFactories;
        factories.RemoveType<FormValueProviderFactory>();
        factories.RemoveType<JQueryFormValueProviderFactory>();
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }
}
like image 18
Sunil Buddala Avatar answered Nov 12 '22 08:11

Sunil Buddala