3

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?

12
  • 2
    Make all your controllers inherit from this (base) controller.
    – haim770
    Sep 20, 2016 at 12:34
  • Yes, I thought about it but is there any other way without inheirt from base controller. Sep 20, 2016 at 12:35
  • You could also probably use a global action filter to inspect the result on the way out of the pipeline. (crosscutting concern)
    – Nkosi
    Sep 20, 2016 at 12:39
  • You can create an extension method to do that. For example, instead of return Json(data) you do return data.AsJson(). Otherwise, you'll have to opt for a global filter.
    – haim770
    Sep 20, 2016 at 12:43
  • @haim770 thanks for your comment. Sep 20, 2016 at 12:56

1 Answer 1

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.