ASP.NET MVC 2.0 JsonRequestBehavior Global Setting

心不动则不痛 提交于 2019-12-02 20:04:55

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(...).

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

MVC 2 block Json for GET requests for security reasons. If you want to override that behavior, check out the overload for Json that accepts a JsonRequestBehavior parameter.

public ActionResult Index()

{

   return Json(data, JsonRequestBehavior.AllowGet)

}
Rod

I also got this error when I first use MVC 2.0 using my old code in MVC 1.0. I use fiddler to identify the cause of the error. See the steps on how to troubleshoot it using Fidder -

http://www.rodcerrada.com/post/2011/07/11/jQuery-getJSON()-does-not-tirgger-the-callback-in-ASPNET-MVC-2.aspx

Is this is the security issue MVC2 was trying to address? http://haacked.com/archive/2009/06/25/json-hijacking.aspx

If so, it seems like the vulnerability is only an issue if you are trying to do a json call to an outside website. If your MVC2 app is only making json calls to your own website (to fill jqgrids for example), shouldn't you be able to safely override the Json call in your base controller to always allow get?

gagan

Just change JSON code from :

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

to:

$.post("methodname/" + ID, null, function (data, textStatus)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!