ASP.NET MVC 2.0 JsonRequestBehavior Global Setting

Viewed 17678

ASP.NET MVC 2.0 will now, by default, throw an exception when an action attempts to return JSON in response to a GET request. I know this can be overridden on a method by method basis by using JsonRequestBehavior.AllowGet, but is it possible to set on a controller or higher basis (possibly the web.config)?

Update: Per Levi's comment, this is what I ended up using-

protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding)
{
    return Json(data, contentType, JsonRequestBehavior.AllowGet);
}
6 Answers

There's another option. Use Action Filters.

Create a new ActionFilterAttribute, apply it to your controller or a specific action (depending on your needs). This should suffice:

public class JsonRequestBehaviorAttribute : ActionFilterAttribute
{
    private JsonRequestBehavior Behavior { get; set; }

    public JsonRequestBehaviorAttribute()
    {
        Behavior = JsonRequestBehavior.AllowGet;
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var result = filterContext.Result as JsonResult;

        if (result != null)
        {
            result.JsonRequestBehavior = Behavior;
        }
    }
}

Then apply it like this:

[JsonRequestBehavior]
public class Upload2Controller : Controller

Just change JSON code from :

$.getJson("methodname/" + ID, null, function (data, textStatus)

to:

$.post("methodname/" + ID, null, function (data, textStatus)
Related