<%@ WebHandler Language="C#" %> using System; using System.Web; using System.Collections.Generic; using System.Threading; using System.Runtime.Serialization.Json; using System.IO; using System.Text; public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; int pn = 0; if (context.Request.QueryString["PageNum"] != null) { if (context.Request.QueryString["PageNum"].ToString().Trim() != string.Empty) { if (int.TryParse(context.Request.QueryString["PageNum"].ToString().Trim(), out pn)) { pn = int.Parse(context.Request.QueryString["PageNum"].ToString().Trim()); } } } List<NewsInfo> ListQuery = NewsInfo.GetListByPn(pn); string ResultJson = "[{\"Num\":-1,\"Ntitle\":\"暂无数据\"}]"; if (ListQuery.Count > 1) { ResultJson = Obj2Json<List<NewsInfo>>(ListQuery); } Thread.Sleep(5000);//因为数据量比较少,这里线程暂停5秒,让页面出现数据加载等待的效果 context.Response.Write(ResultJson); } /// <summary> /// List转Json /// </summary> /// <typeparam></typeparam> /// <param></param> /// <returns></returns> public static string Obj2Json<T>(T t) { try { DataContractJsonSerializer serializer = new DataContractJsonSerializer(t.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, t); return Encoding.UTF8.GetString(ms.ToArray()); } } catch { return null; } } public bool IsReusable { get { return false; } } }
代码就是这些了,现在运行看一下页面的效果如何。