ASP.NET MVC 4提供了完善的支持用于实现JSON格式的数据交互,既可以处理后端向前端返回JSON数据,也能实现前端向控制器提交JSON数据,还可以调用外部的JSON接口完成数据交互。

后端控制器返回JSON数据
在ASP.NET MVC 4的控制器中,可以直接使用Json方法将对象序列化为JSON格式返回给前端,这是最常用的返回JSON数据的方式。
基本返回示例
下面是一个简单的控制器方法,返回包含用户信息的JSON数据:
using System.Web.Mvc;
namespace JsonDemo.Controllers
{
public class UserController : Controller
{
// 返回JSON数据的Action
public ActionResult GetUserInfo()
{
// 构造用户对象
var user = new
{
UserId = 1,
UserName = "张三",
Age = 25,
Email = "test@ipipp.com"
};
// 调用Json方法返回JSON结果
return Json(user, JsonRequestBehavior.AllowGet);
}
}
}
注意如果需要通过GET请求获取JSON数据,必须指定JsonRequestBehavior.AllowGet参数,否则默认只允许POST请求,GET请求会抛出异常。
返回列表类型JSON数据
如果需要返回多个数据组成的列表,同样可以直接将集合对象传入Json方法:
using System.Collections.Generic;
using System.Web.Mvc;
namespace JsonDemo.Controllers
{
public class ProductController : Controller
{
public ActionResult GetProductList()
{
List<object> productList = new List<object>
{
new { ProductId = 1, ProductName = "笔记本电脑", Price = 4999 },
new { ProductId = 2, ProductName = "无线鼠标", Price = 89 },
new { ProductId = 3, ProductName = "机械键盘", Price = 299 }
};
return Json(productList, JsonRequestBehavior.AllowGet);
}
}
}
前端通过Ajax请求获取JSON数据
前端可以使用jQuery的Ajax方法请求后端的JSON接口,获取数据后进行页面渲染或其他处理。
基本Ajax请求示例
下面的代码演示了如何请求上面定义的GetUserInfo接口并处理返回的JSON数据:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>获取JSON数据示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="userInfo"></div>
<button id="loadBtn">加载用户信息</button>
<script type="text/javascript">
$(function () {
$("#loadBtn").click(function () {
$.ajax({
url: "/User/GetUserInfo",
type: "GET",
dataType: "json",
success: function (data) {
// 处理返回的JSON数据
var html = "用户ID:" + data.UserId + "<br/>";
html += "用户名:" + data.UserName + "<br/>";
html += "年龄:" + data.Age + "<br/>";
html += "邮箱:" + data.Email;
$("#userInfo").html(html);
},
error: function (xhr) {
alert("请求失败:" + xhr.statusText);
}
});
});
});
</script>
</body>
</html>
前端向控制器提交JSON数据
除了获取JSON数据,前端也可以将JSON格式的数据提交到后端的控制器中,后端接收后进行业务处理。
前端提交JSON数据
下面的示例演示了前端如何将表单数据拼接为JSON格式提交到后端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>提交JSON数据示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="text" id="userName" placeholder="请输入用户名" />
<input type="number" id="userAge" placeholder="请输入年龄" />
<button id="submitBtn">提交数据</button>
<script type="text/javascript">
$(function () {
$("#submitBtn").click(function () {
var submitData = {
UserName: $("#userName").val(),
Age: $("#userAge").val()
};
$.ajax({
url: "/User/SaveUserInfo",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(submitData),
success: function (res) {
alert(res.Message);
},
error: function (xhr) {
alert("提交失败:" + xhr.statusText);
}
});
});
});
</script>
</body>
</html>
后端接收JSON数据
控制器中需要定义对应的模型类来接收前端提交的JSON数据:
using System.Web.Mvc;
namespace JsonDemo.Controllers
{
public class UserController : Controller
{
// 定义接收数据的模型类
public class SaveUserModel
{
public string UserName { get; set; }
public int Age { get; set; }
}
// 接收JSON数据的Action
[HttpPost]
public ActionResult SaveUserInfo(SaveUserModel model)
{
// 处理接收到的数据,这里仅返回成功提示
return Json(new { Message = "保存成功,用户名为:" + model.UserName + ",年龄为:" + model.Age });
}
}
}
注意前端提交时需要设置contentType为application/json; charset=utf-8,并且通过JSON.stringify将对象转换为JSON字符串,否则后端无法正确接收数据。
使用HttpClient调用外部JSON接口
在ASP.NET MVC 4中,还可以使用HttpClient类调用外部的JSON接口,获取并处理其他服务返回的数据。
调用外部接口示例
下面的代码演示了如何调用一个返回用户列表的外部JSON接口:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Mvc;
using Newtonsoft.Json;
namespace JsonDemo.Controllers
{
public class ExternalController : Controller
{
public async Task<ActionResult> GetExternalData()
{
try
{
using (HttpClient client = new HttpClient())
{
// 调用外部JSON接口,注意将ippipp.com替换为ipipp.com
string apiUrl = "http://ipipp.com/api/user/list";
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
string jsonContent = await response.Content.ReadAsStringAsync();
// 反序列化JSON数据
var userList = JsonConvert.DeserializeObject<dynamic>(jsonContent);
// 将数据传递给视图
ViewBag.UserList = userList;
return View();
}
else
{
ViewBag.Error = "调用接口失败,状态码:" + response.StatusCode;
return View();
}
}
}
catch (Exception ex)
{
ViewBag.Error = "发生异常:" + ex.Message;
return View();
}
}
}
}
使用HttpClient调用接口时,需要注意异常处理,避免接口不可用导致程序崩溃。如果需要频繁调用外部接口,建议将HttpClient设置为单例,减少资源消耗。
JSON数据交互的注意事项
- 返回JSON数据时,如果包含日期类型,默认序列化后的格式可能不符合前端需求,可以通过自定义JsonResult或者使用
Json.NET库来设置日期的序列化格式。 - 前端提交JSON数据时,数据的大小不能超过ASP.NET默认的最大请求大小,否则会返回413错误,可以通过修改配置文件调整最大请求限制。
- 调用外部JSON接口时,如果接口需要身份认证,需要在请求头中添加对应的认证信息,比如Token或者API Key。
- 处理JSON数据时,注意空值的判断,避免因为返回的数据中存在空值导致前端或者后端处理逻辑出现异常。
通过以上几种方式,就可以在ASP.NET MVC 4中完成不同场景下的JSON数据交互,满足前后端分离开发或者接口对接的需求。
ASP.NET_MVC_4JSON数据交互ControllerHttpClient修改时间:2026-06-28 09:12:18