• ASP.NET MVC2中返回Json异常的解决办法


    ASP.NET MVC2中返回Json异常的解决办法

    在ASP.NET MVC1.0中,我们在前段通常会这样做。

                $.ajax({
                        type: 
    "GET",
                        url: 
    "/role/SaveRoleResource",
                        data: { roleId: roleId, array: item },
                        datatype: 
    'json',
                        success: 
    function (result) {
                            alert(result);
                        },
                        error: 
    function (result1) {
                            alert(result1);
                        }
               });

    或者

     

                     $.getJSON("/role/SaveRoleResource", { roleId: roleId, array: item },
                                                
    function (data) {
                                                    alert(data);
                                                });

    后端我们会做这样的代码:

            public ActionResult SaveRoleResource(int roleId,Array array)
            {
                
    int count = RoleResourceDal.Update(roleId, array);

                
    return Json(count);
            }

    同样的代码如果放到ASP.NET MVC2中,就会报如下异常:

     [InvalidOperationException]: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

    解决方法,将后端代码改成如下

            public ActionResult SaveRoleResource(int roleId,Array array)
            {
                
    int count = RoleResourceDal.Update(roleId, array);

                
    return Json(count,JsonRequestBehavior.AllowGet);
            }

    看到这里,可能您就会明白,ASP.NET MVC2中JsonRequestBehavior默认是JsonRequestBehavior.DenyGet。

    错误信息:

    System.InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

    由错误信息可知MVC2出于对网站数据的保护,默认禁止通过get的请求返回JsonResult数据,你可以在返回Json时,传入第二个参数JsonRequestBehavior.AllowGet。

    如:return Json(result, JsonRequestBehavior.AllowGet)。

    当然你也可以修改你的前端代码,使用post的方式来获取数据。

  • 相关阅读:
    [转]在自己的项目中调用别人的库的方法(static lib库,dynamic lib库以及dll动态库)
    前端、后台、客户端以及服务器
    C# 使用j
    C# Linq技术中SelectMany() 获取list对象的属性 汇总成为一个新的集合
    C# 集合的扩展方法-查询表达式GroupBy()的使用 转
    C# ASP.NET MVC中Filter过滤器的使用 通过注册到Global.asax注册为全局 过滤所有action
    C# ASP.NET MVC中有四种Filter 过滤器类型 通过标签 Attribute加到action上面
    C# 《Asp.Net Web Api 》-----路由机制 转
    C# ASP.NET MVC5路由系统机制详细讲解(转)
    MVC 自定义数据校验规则 Validation
  • 原文地址:https://www.cnblogs.com/fx2008/p/2283105.html
Copyright © 2020-2023  润新知