0

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.

A. Gladkiy
  • 3,134
  • 5
  • 38
  • 82
  • Since the stream reader is being read using the 'Using' statement, it might be getting disposed at the end of the block and becomes unavailable for the subsequent read. Try avoiding dispose of the stream. – Ritesh Kulkarni Jan 29 '20 at 12:45

1 Answers1

2

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.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • I can't store it in variable because I need 2 ways: 1. From UI I need to check file and then after user click Create, I need to create (so it's 2 separate queries) 2. From API I need to check file and create in one API call – A. Gladkiy Jan 29 '20 at 12:52
  • 1
    You can always store it in a variable. If you want the entire request body at once, copy the request stream to your own stream. The request stream (request.InputStream) is a read-once stream. You can reset your own MemoryStream, for example, if you copy it to that. The drawback is that then you need the entire input in memory. – CodeCaster Jan 29 '20 at 13:03