ASP.NET MVC 2.0 JsonRequestBehavior全局设置 [英] ASP.NET MVC 2.0 JsonRequestBehavior Global Setting

查看:113
本文介绍了ASP.NET MVC 2.0 JsonRequestBehavior全局设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET MVC 2.0,现在,在默认情况下,抛出一个异常,当一个操作试图在响应GET请求,返回JSON。我知道这可以通过方法基础上的方法,通过使用JsonRequestBehavior.AllowGet被覆盖,但有可能控制器或更高的基础上(可能在web.config)?

上设置

更新:每列维的评论,这是我结束了使用 -

 保护覆盖JsonResult JSON(对象数据串的contentType,System.Text.Encoding contentEncoding)
{
    返回JSON(数据,则contentType,JsonRequestBehavior.AllowGet);
}


解决方案

这,像其他MVC特定的设置,是不是通过Web.config中设置的。但是,你有两个选择:


  1. 重写Controller.Json(对象,字符串编码)超载调用JSON(对象,字符串编码,JsonRequestBehavior),传递的 JsonRequestBehavior.AllowGet 的作为最后一个参数。如果你想这适用于所有的控制器,然后做一个这样的抽象基控制器类里面,然后让所有的控制器继承该抽象类。


  2. 请扩展方法MyJson(此控制器,...),它创建了一个JsonResult,并设置相应的属性,然后经由this.MyJson控制器(...)来调用它。


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);
}

解决方案

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

这篇关于ASP.NET MVC 2.0 JsonRequestBehavior全局设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆