ASP.net MVC: Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''.

ASP.net MVC: Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''.

December 27, 2014

While walking through an ASP.net MVC3 app, I noticed that Ajax calls resulted in nothing happening. Debugging in Visual Studio, I noticed a SerializationException at the following code:

1
public override void OnActionExecuting(ActionExecutingContext filterContext) {.object o = new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);}

The JSON response from the Ajax was supposed to be read here, but it was failing. It was a runtime exception, “SerializationException was unhandled by user code.” Turns out InputStream wasn’t being read from the beginning of the stream, so the JSON couldn’t be deserialized properly.

Resetting the position in the current stream to the beginning should make it readable again:

1
public override void OnActionExecuting(ActionExecutingContext filterContext) {.//move current position in the stream back to the beginningfilterContext.HttpContext.Request.InputStream.Position = 0;object o = new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);}