ASP.NET 处理 JSON

作为后端,有可能需要接收来自前端提交的 json 格式的数据,也有可能需要往前端发送 json 格式的数据,这里以分类作为示例,介绍下在 ASP.NET 处理程序中是如何跟前端进行数据交换的。

public class CategoryHandler : IHttpHandler {
	public bool IsReusable  { get { return true; } }
	
	public void ProcessRequest(HttpContext context) {
		// DbEntities 是 ADO.NET 实体数据模型。
		// 其中 category 对应的就是对应数据库中的分类表,包含 id 和 name 两个字段。
	    DbEntities entities = new DbEntities();

		// 提供序列化和反序列化的对象
	    JavaScriptSerializer serializer =  new JavaScriptSerializer();
	    
	    // 根据访问路径的后缀决定做出什么动作
	    string path = context.Request.Path;
	    // 针对 post 请求做不同的处理
	    string method = context.Request.HttpMethod;
	    if (method.Equals(WebRequestMethods.Http.Post)) {
	        if (path.EndsWith("add")) {
	            // 新增
	            // 针对前端数据在 【FormData】中
	            string name = context.Request.Form["name"]; 
	            category c = new category();
	            c.name = name;
	            entities.category.Add(c);
	            entities.SaveChanges();
	        } else if (path.EndsWith("adds")) {
	            // 批量新增
	            // 针对前端数据在 【Request Payload】中
	            Stream stream = context.Request.InputStream;
	            StreamReader reader = new StreamReader(stream);
	            List<category> cs = serializer.Deserialize<List<category>>(reader.ReadToEnd());
	            foreach (category c in cs) {
	                Debug.WriteLine(c);
	                // 如果不存在的情况下,考虑新增
	                if (!entities.category.Any(a => a.Id == c.Id)) {
	                    entities.category.Add(c);
	                }
	                entities.SaveChanges();
	            }
	        } else if (path.EndsWith("delete")) {
	            // 处理删除
	            // 针对前端数据在 【QueryString】中
	            category c = new category();
	            c.Id = Convert.ToInt32(context.Request.Params["id"]);
	                // 如果存在的情况下,考虑删除
	            if (entities.category.Any(a => a.Id == c.Id)) {
	                entities.category.Attach(c);
	                entities.category.Remove(c);
	                entities.SaveChanges();
	            }
	        }
	    }
	
		// 无论什么请求,都返回所有的分类数据
		IEnumerable<category> categories = entities.category.Where(a => a.Id > 0);
		context.Response.ContentType = "application/json";
		context.Response.Write(serializer.Serialize(categories));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值