Search code examples
c#filestreamstreamreadermemorystreamhttpfilecollection

HttpPostedFileBase ContentLength = 0 after reading


I send json file to server and want to read that twice.

[HttpPost]
public ActionResult CreateCases(string fileFormat, Guid key)
{
    var file = Request.Files[0];
    CheckFile(file);
    Create(file);

    return Json();
}

public object Check(HttpPostedFileBase file)
{
    var stream = file.InputStream;
    var serializer = new JsonSerializer();
    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        dynamic json = serializer.Deserialize(jsonTextReader);
        ...
    }
}

public object Create(HttpPostedFileBase file)
{
    var stream = file.InputStream;
    var serializer = new JsonSerializer();
    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        dynamic json = serializer.Deserialize(jsonTextReader);
        ...
    }
}

In Check method file.ContentLength = right value

In Create method file.ContentLength = 0 and json variable already = null

What am I doing wrong? Thanks in advance.


Solution

  • What am I doing wrong?

    This:

    I [...] want to read that [file] twice

    Your client only sends the file to your web application once, so you should only read it once.

    Sure, you can rewind the input stream and appear to solve the immediate problem, but that just introduces new problems, because now you have the entire file in memory at once - and your code can only continue once the entire request has been read.

    You don't want to read the file twice.

    If you want to validate, then process the JSON, then obtain the JSON, store it in a variable, and then validate and process that variable. Yes, this still requires you to read the entire request body, but then that's your requirement.