前台JSON格式数据如何传递给后台CS接收
在Web开发中,前端与后端的数据交互是核心环节,JSON(JavaScript Object Notation)因其轻量级、易读、跨语言等特性,已成为前后端数据交互的主流格式,本文将详细介绍前端如何将JSON格式数据传递给后台C#(通常指ASP.NET或ASP.NET Core),以及后台如何正确接收和解析这些数据。
前端发送JSON数据的常见场景
前端发送JSON数据主要通过HTTP请求实现,常见场景包括:
- 表单提交:将表单数据封装为JSON,通过POST请求发送;
- AJAX请求:异步请求中传递JSON数据,实现页面无刷新交互;
- 文件上传:附带JSON元数据的文件上传请求;
- API调用:前端调用后端RESTful API时传递JSON参数。
前端发送JSON数据的正确姿势
设置请求头(Content-Type)
前端发送JSON数据时,必须明确告知服务器请求体的格式,通过Content-Type: application/json
声明,使用fetch
API发送POST请求:
// 示例:使用fetch发送JSON数据 const data = { username: "zhangsan", age: 25, hobbies: ["reading", "coding"] }; fetch("https://example.com/api/user", { method: "POST", headers: { "Content-Type": "application/json" // 关键:声明JSON格式 }, body: JSON.stringify(data) // 将对象转为JSON字符串 }) .then(response => response.json()) .then(result => console.log("后端返回:", result)) .catch(error => console.error("请求失败:", error));
注意事项
- body必须是JSON字符串:直接传递JavaScript对象会报错,需通过
JSON.stringify()
序列化; - 避免CORS问题:跨域请求需后端配置
Access-Control-Allow-Origin
等响应头; - 数据编码:JSON默认使用UTF-8编码,无需额外处理。
后台C#接收JSON数据的核心方法
后台C#接收JSON数据的核心是“反序列化”——将JSON字符串转换为C#对象,根据后端框架(ASP.NET Web API/ASP.NET Core)和请求场景的不同,接收方式略有差异。
场景1:接收POST请求的JSON体(如用户注册、数据提交)
(1)ASP.NET Web API(.NET Framework 4.x+)
通过[FromBody]
特性标记参数,框架会自动反序列化请求体为C#对象。
步骤:
-
定义C#模型类(属性名需与JSON键名一致,区分大小写):
public class UserModel { public string Username { get; set; } public int Age { get; set; } public List<string> Hobbies { get; set; } }
-
在Controller中接收JSON数据:
using System.Web.Http; public class UserController : ApiController { [HttpPost] public IHttpActionResult CreateUser([FromBody] UserModel user) // [FromBody]标记从请求体获取 { if (user == null) return BadRequest("请求数据为空"); // 处理业务逻辑(如存入数据库) Console.WriteLine($"接收到用户: {user.Username}, 年龄: {user.Age}"); Console.WriteLine("爱好:" + string.Join(", ", user.Hobbies)); return Ok(new { success = true, message = "用户创建成功" }); } }
原理:ASP.NET Web API使用MediaTypeFormatter
(默认JsonMediaTypeFormatter
)自动解析Content-Type: application/json
的请求体,调用JsonConvert.DeserializeObject<T>
(Newtonsoft.Json)将JSON转为C#对象。
(2)ASP.NET Core(.NET 6/7/8+)
ASP.NET Core的接收方式与Web API类似,但内置了更强大的JSON序列化(System.Text.Json
,也可配置Newtonsoft.Json)。
步骤:
-
定义C#模型类(与Web API一致):
public class UserModel { public string Username { get; set; } public int Age { get; set; } public List<string> Hobbies { get; set; } }
-
在Controller中接收(无需额外引入Newtonsoft.Json时):
using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class UserController : ControllerBase { [HttpPost] public IActionResult CreateUser([FromBody] UserModel user) // [FromBody]标记 { if (user == null) return BadRequest("请求数据为空"); // 处理业务逻辑 Console.WriteLine($"接收到用户: {user.Username}, 年龄: {user.Age}"); Console.WriteLine("爱好:" + string.Join(", ", user.Hobbies)); return Ok(new { success = true, message = "用户创建成功" }); } }
进阶:若需使用Newtonsoft.Json(如兼容旧项目或依赖特定功能),在Program.cs
中配置:
builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; // 禁用驼峰命名(默认启用) }) .AddNewtonsoftJson(); // 启用Newtonsoft.Json
场景2:接收URL中的JSON参数(如GET请求或动态参数)
(1)通过路由模板传递JSON字符串
前端将JSON对象序列化为字符串,作为URL的一部分传递(需URL编码):
const data = { id: 1, name: "test" }; const queryString = encodeURIComponent(JSON.stringify(data)); // URL编码 fetch(`/api/user/get?data=${queryString}`, { method: "GET" })
后台通过[FromQuery]
接收并解析:
[HttpGet("get")] public IActionResult GetUser([FromQuery] string data) { if (string.IsNullOrEmpty(data)) return BadRequest("参数缺失"); // 反序列化JSON字符串 var user = System.Text.Json.JsonSerializer.Deserialize<UserModel>(data); return Ok(user); }
(2)通过路由参数传递JSON字段
若JSON结构简单,可直接映射到路由参数:
// 前端:URL传递id和name fetch("/api/user/123/test")
后台通过[FromRoute]
接收:
[HttpGet("{id}/{name}")] public IActionResult GetUser([FromRoute] int id, [FromRoute] string name) { return Ok(new { id, name }); }
场景3:接收表单提交的JSON(非标准表单数据)
若前端使用application/x-www-form-urlencoded
但传递JSON字符串(不推荐,但可能遇到),可通过[FromForm]
接收并手动解析:
[HttpPost("submit-form")] public IActionResult SubmitForm([FromForm] string formData) { // formData是JSON字符串,手动反序列化 var data = System.Text.Json.JsonSerializer.Deserialize<UserModel>(formData); return Ok(data); }
常见问题与解决方案
JSON键名与C#属性名不一致
-
解决方案1:使用
[JsonPropertyName]
特性(System.Text.Json)或[JsonProperty]
(Newtonsoft.Json)指定映射关系:using System.Text.Json.Serialization; public class UserModel { [JsonPropertyName("user_name")] // 对应JSON中的"user_name" public string Username { get; set; } }
-
解决方案2:启用驼峰命名(默认启用),确保JSON使用
userName
而非username
。
接收复杂嵌套JSON
若JSON包含嵌套对象或数组,C#模型需对应定义嵌套结构:
{ "id": 1, "info": { "address": "北京", "phone": "13800138000" }, "orders": [ { "orderNo": "A001", "amount": 100 }, { "orderNo": "A002", "amount": 200 } ] }
对应C#模型:
public class Order { public string OrderNo { get; set; } public decimal Amount { get; set; } } public class UserInfo { public string Address { get; set; } public string Phone { get; set; } } public class UserWithOrders { public int Id { get; set; } public UserInfo Info { get; set; } public List<Order> Orders { get; set; } }
反序列化失败(如JSON格式错误)
- 捕获异常:用
try-catch
包裹反序列化代码,避免程序崩溃:try { var user = System.Text.Json.JsonSerializer.Deserialize
还没有评论,来说两句吧...