ASP.NET MVC JsonResult返回500

我有这个控制器方法:

public JsonResult List(int number) { var list = new Dictionary(); list.Add(1, "one"); list.Add(2, "two"); list.Add(3, "three"); var q = (from h in list where h.Key == number select new { key = h.Key, value = h.Value }); return Json(list); } 

在客户端,有这个jQuery脚本:

 $("#radio1").click(function () { $.ajax({ url: "/Home/List", dataType: "json", data: { number: '1' }, success: function (data) { alert(data) }, error: function (xhr) { alert(xhr.status) } }); }); 

我总是收到错误代码500.问题是什么?

谢谢

如果你看到实际的反应,它可能会说

此请求已被阻止,因为在GET请求中使用此信息时,可能会向第三方网站披露敏感信息。 要允许GET请求,请将JsonRequestBehavior设置为AllowGet。

您需要使用重载的Json构造函数来包含JsonRequestBehaviorJsonRequestBehavior.AllowGet例如:

 return Json(list, JsonRequestBehavior.AllowGet); 

这是它在你的示例代码中的样子(注意这也会将你的int更改为string s,否则你会得到另一个错误)。

 public JsonResult List(int number) { var list = new Dictionary(); list.Add("1", "one"); list.Add("2", "two"); list.Add("3", "three"); var q = (from h in list where h.Key == number.ToString() select new { key = h.Key, value = h.Value }); return Json(list, JsonRequestBehavior.AllowGet); } 

虽然JustinStolle的答案解决了您的问题,但我会注意框架提供的错误。 除非您有充分的理由想要使用GET方法发送数据,否则您应该使用POST方法发送它。

问题是,当您使用GET方法时,您的参数会添加到您的请求url中,而不是添加到请求的标头/正文中。 这似乎是一个微小的差异,但错误暗示了它为什么重要。 发送方和接收方之间的代理服务器和其他潜在服务器易于记录请求url,并且经常忽略请求的标头和/或正文。 此信息通常也被视为非重要/秘密,因此默认情况下,URL中公开的任何数据都不太安全。

最佳做法是使用POST方法发送数据,以便将数据添加到正文而不是url。 幸运的是,这很容易改变,特别是因为你正在使用jquery。 您可以使用$.post包装器或向参数添加类型:“POST”:

 $.ajax({ url: "/Home/List", type: "POST", dataType: "json", data: { number: '1' }, success: function (data) { alert(data) }, error: function (xhr) { alert(xhr.status) } });