Wednesday, February 1, 2012

ASP.NET MVC: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

When loading a big JsonResult from the server, the request fails with the following error message:

“InvalidOperationException:Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.”

Thanks to this descriptive error message, its quiet clear what’s happening. The size of the JSON object exceeds the maxJsonLength value of the JavaScriptSerializer class that’s used behind the scenes.

But how can we change this value?

You cannot access this property directly through the JsonResult. Instead you can create your own result:

public class ExtendedJsonResult : ActionResult
{
public ExtendedJsonResult()
{
this.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
this.MaxJsonLength=Int.MaxValue;
}

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
}
HttpResponseBase response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = this.ContentType;
}
else
{
response.ContentType = "application/json";
}
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength=this.MaxJsonLength;
response.Write(serializer.Serialize(this.Data));
}
}

public Encoding ContentEncoding { get; set; }

public string ContentType { get; set; }

public object Data { get; set; }

public JsonRequestBehavior JsonRequestBehavior { get; set; }

public int MaxJsonLength{get;set;}
}

No comments: