Reputation: 4574
I had a problem regarding MaxJsonLength
in MVC. The problem occurred when i returned json()
. Then i found a solution here (please read this) answered by fanisch. Now i have many controllers where i have problem of MaxJsonLength
. I want to override this method globally.
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}
How can i do this? Is there any way to impliment this method globally or should i use action filters?
Upvotes: 3
Views: 548
Reputation: 62213
The easiest way to to create an extension method (totally in agreement with other comments on the OP that said the same). Here is an implementation of your method in your OP as an extension method. You can rename it as you see fit. I also added some defaults to the parameters which are the same as those used in the method overloads of the controller.
public static class ControllerExtensions {
public static JsonResult AsJson(this Controller controller, object data, JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet, string contentType = null, System.Text.Encoding contentEncoding = null)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}
}
// how to call from inside an action (method) on a controller
public class SomeController : Controller {
public JsonResult GetSomething(){
return this.AsJson(new {prop1 = "testing"});
}
}
For more on extension methods see Extension Methods
Upvotes: 3