public class Post { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } }
public class Blog { public List<Post> Posts { get; set; } }
public class BlogHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; List<Post> posts = new List<Post>() { new Post{ Id=1, Title="一步一步学Silverlight 2系列(13):数据与通信之WebRequest", Author="TerryLee" }, new Post{ Id=2, Title="一步一步学Silverlight 2系列(12):数据与通信之WebClient", Author="TerryLee" }, new Post{ Id=3, Title="一步一步学Silverlight 2系列(11):数据绑定", Author="TerryLee" }, new Post{ Id=4, Title="一步一步学Silverlight 2系列(10):使用用户控件", Author="TerryLee" }, new Post{ Id=5, Title="一步一步学Silverlight 2系列(9):使用控件模板", Author="TerryLee" }, new Post{ Id=6, Title="一步一步学Silverlight 2系列(8):使用样式封装控件观感", Author="TerryLee" } }; Blog blog = new Blog(); blog.Posts = posts; context.Response.Write(JavaScriptConvert.SerializeObject(blog)); } public bool IsReusable { get { return false; } } }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { Uri endpoint = new Uri("http://localhost:8081/BlogHandler.ashx"); WebRequest request = WebRequest.Create(endpoint); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.BeginGetResponse(new AsyncCallback(ResponseReady), request); } void ResponseReady(IAsyncResult asyncResult) { WebRequest request = asyncResult.AsyncState as WebRequest; WebResponse response = request.EndGetResponse(asyncResult); using (Stream responseStream = response.GetResponseStream()) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Blog)); Blog blog = jsonSerializer.ReadObject(responseStream) as Blog; Posts.ItemsSource = blog.Posts; } }
本文出自 “TerryLee技术专栏” 博客,请务必保留此出处http://terrylee.blog.51cto.com/342737/67254
本文出自 51CTO.COM技术博客