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的方式来获取数据。

 

 

你可能感兴趣的:(asp.net)