若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet(转载)

若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet

若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet

请将 JsonRequestBehavior 设置为 AllowGet

MVC 默认 Request 方式为 Post。
action

复制代码
public JsonResult GetPersonInfo()  {  
  var person = new  {  
    Name = "张三",  
    Age = 22,  
    Sex = "男"  
  };  
  return Json(person);  
}  
复制代码

或者

复制代码
 1 public JsonResult GetPersonInfo()  {  
 2   return Json (new{Name = "张三",Age = 22,Sex = "男"});  
 3 }  
 4 view  
 5 $.ajax({  
 6   url: "/FriendLink/GetPersonInfo",  
 7   type: "POST",  
 8   dataType: "json",  
 9   data: { },  
10   success: function(data) {  
11      $("#friendContent").html(data.Name);  
12   }  
13 })  
复制代码

POST 请求没问题,GET 方式请求出错:

解决方法
json方法有一个重构:

复制代码
1 public JsonResult GetPersonInfo()  {  
2   var person = new  {  
3       Name = "张三",  
4       Age = 22,  
5       Sex = "男"  
6    };  
7    return Json(person,JsonRequestBehavior.AllowGet);  
8 }  
复制代码

这样一来我们在前端就可以使用Get方式请求了:

1 $.getJSON("/FriendLink/GetPersonInfo", null, function(data) {  
2     $("#friendContent").html(data.Name);  
3 })  
作者:chenze
出处:https://www.cnblogs.com/chenze-Index/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果文中有什么错误,欢迎指出。以免更多的人被误导。
原文地址:https://www.cnblogs.com/chenze-Index/p/9293655.html