In ASP.NET MVC 3 RC2, the default ModelBinder will automatically parse the request body if the Content-Type
is set to application/json
. Problem is, this leaves the Request.InputStream
at the end of the stream. This means that if you try to read the input stream using your own code, you first have reset it back to the beginning:
// client sends HTTP request with Content-Type: application/json and a JSON
// string in the body
// requestBody is null because the stream is already at the end
var requestBody = new StreamReader(Request.InputStream).ReadToEnd();
// resets the position back to the beginning of the input stream
var reader = new StreamReader(Request.InputStream);
reader.BaseStream.Position = 0;
var requestBody = reader.ReadToEnd();
Since I'm using Json.NET
to do my serialization/deserialization, I'd like to disable the default ModelBinder from doing this extra parsing. Is there any way to do that?
You can put the following in Application_Start in your Global.asax:
ValueProviderFactories.Factories.Remove(
ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().First());
This assumes there is only one of that type (which by default there is), but it can easily be changed to work if there is more than one. I don't believe there is a cleaner way if that is what you are looking for.