Specified method is not supported while using SeekOrigin.Begin on stream

Viewed 1564

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.

1 Answers

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.

Related