Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 2.0 JsonRequestBehavior Global Setting

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); } 
like image 548
beckelmw Avatar asked Nov 02 '09 19:11

beckelmw


1 Answers

This, like other MVC-specific settings, is not settable via Web.config. But you have two options:

  1. Override the Controller.Json(object, string, Encoding) overload to call Json(object, string, Encoding, JsonRequestBehavior), passing JsonRequestBehavior.AllowGet as the last argument. If you want this to apply to all controllers, then do this inside an abstract base controller class, then have all your controllers subclass that abstract class.

  2. Make an extension method MyJson(this Controller, ...) which creates a JsonResult and sets the appropriate properties, then call it from your controller via this.MyJson(...).

like image 152
Levi Avatar answered Oct 13 '22 23:10

Levi