5

I have a StreamReader which I am using to deserialize my request later on as shown below -

Here s is Stream object -

using (var reader = new StreamReader(s))
{
    using (var jsonReader = new JsonTextReader(reader))
    {
        var ser = new JsonSerializer();
        return ser.Deserialize<T>(jsonReader);
    }
}

Everything works fine but now I am trying to print the actual request body on the console so I tried like this but it gives me an error -

using (var reader = new StreamReader(s))
{
    string body = reader.ReadToEnd();
    // print body on the console which is what I am trying to do
    // reset to start of stream
    // this line gives me error
    s.Seek(0, SeekOrigin.Begin);
    using (var jsonReader = new JsonTextReader(reader))
    {
        var ser = new JsonSerializer();
        return ser.Deserialize<T>(jsonReader);
    }
}

After this change, I am getting an error as - Specified method is not supported. I am not sure what wrong I am doing here.

Note: This is just for debugging purpose only that I want to print the body on console. After that I will remove reader.ReadToEnd(); stuff.

AndyP
  • 527
  • 1
  • 14
  • 36
  • 1
    If you've already read the stream content in `body`, why don't you deserialize this string instead of reading the stream again? – Marco Jun 08 '21 at 21:29
  • I am just trying to print the request body as a string on the console which is coming to this method so I came up with this quick way before it can be deserialized. I didn't realize we can that too. My main idea is to print the request body as a string on console and also deserialize it the way it is doing currently. – AndyP Jun 08 '21 at 21:31
  • It's a nonsense: either you deserialize the stream OR you read the whole stream content and deserialize the string. Reading the stream twice is a waste of resources IMHO – Marco Jun 08 '21 at 21:32
  • From the help on this exception: The stream does not support seeking, such as if the stream is constructed from a pipe or console output. So it looks like you will need to change your approach or construct the stream so it supports Seek() method. [link](https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.seek?view=net-5.0) – David Glass Jun 08 '21 at 21:33
  • 1
    This is just for debugging purpose only. After that I will remove `reader.ReadToEnd();` stuff. – AndyP Jun 08 '21 at 21:34

1 Answers1

5

Not all streams support seeking. Stream has the CanSeek property, which is probably false in this case.

In this specific case, since you're reading the whole message into a string anyway, you can create a StringReader from the string and pass that into JsonTextReader instead of the StreamReader.

In other cases, you may need to find a different solution. For example, if you're reading an ASP.NET Core request stream, you can enable buffering to allow the stream to be read multiple times.

Stephen Jennings
  • 12,494
  • 5
  • 47
  • 66