WCF4.0 –- RESTful WCF Services (1) (入门) 【转】
http://blog.csdn.net/fangxing80/article/details/6235662
WCF 很好的支持了 REST 的开发, 而 RESTful 的服务通常是架构层面上的考虑。 因为它天生就具有很好的跨平台跨语言的集成能力,几乎所有的语言和网络平台都支持 HTTP 请求,无需去实现复杂的客户端代理,无需使用复杂的数据通讯方式既可以将我们的服务暴露给任何需要的人,无论他使用 VB、Ruby、JavaScript,甚至是 HTML FORM,或者直接在浏览器地址栏输入。 WCF 中通过 WebGetAttribute、WebInvokeAttribute (GET/PUT/POST/DELETE)、UriTemplate 定义 REST 的服务的调用方式, 通过 WebMessageFormat (Xml/Json) 定义消息传递的格式。
1. 契约
- using System;
- using System.Collections.Generic;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- namespace WcfRESTfulSvc1
- {
- [ServiceContract]
- public interface ITaskService
- {
- [OperationContract]
- [WebGet(UriTemplate="Tasks/Xml", ResponseFormat=WebMessageFormat.Xml)]
- List<Task> GetTasksXml();
- [OperationContract]
- [WebGet(UriTemplate = "Tasks/Json", ResponseFormat = WebMessageFormat.Json)]
- List<Task> GetTasksJson();
- [OperationContract]
- [WebInvoke(UriTemplate="Task/{title}", Method="GET", ResponseFormat=WebMessageFormat.Json)]
- Task GetTasksByTitle(string title);
- }
- [DataContract]
- public class Task
- {
- [DataMember]
- public string Title { get; set; }
- [DataMember]
- public string Detail { get; set; }
- [DataMember]
- public DateTime CreatedDate { get; set; }
- }
- }
2. 实现
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace WcfRESTfulSvc1
- {
- public class TaskService : ITaskService
- {
- public List<Task> GetTasksXml()
- {
- return GetData();
- }
- public List<Task> GetTasksJson()
- {
- return GetData();
- }
- public Task GetTasksByTitle(string title)
- {
- return GetData().Where(t => t.Title == title).FirstOrDefault();
- }
- private static List<Task> GetData()
- {
- return new List<Task>
- {
- new Task { Title="Task1", Detail="Do Something 1", CreatedDate=DateTime.Now },
- new Task { Title="Task2", Detail="Do Something 2", CreatedDate=DateTime.Now },
- new Task { Title="Task3", Detail="Do Something 3", CreatedDate=DateTime.Now },
- new Task { Title="Task4", Detail="Do Something 4", CreatedDate=DateTime.Now },
- new Task { Title="Task5", Detail="Do Something 5", CreatedDate=DateTime.Now },
- };
- }
- }
- }
通过 WCF 4.0 里创建的 WCF Service Application 发布REST服务很简单,只需要在 svc 的 Markup 里加上 Factory: <%@ ServiceHost Language="C#" Debug="true" Service="WcfRESTfulSvc1.TaskService" CodeBehind="TaskService.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%> BTW: 不过这样,WCF的Metadata就不能访问到了,也就说不能访问到svc的wsdl了。
OK,在浏览器中键入 http://localhost:2571/TaskService.svc/Tasks/Xml 就能得到结果:
- <ArrayOfTask xmlns="http://schemas.datacontract.org/2004/07/WcfRESTfulSvc1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
- <Task>
- <CreatedDate>2011-03-09T21:51:13.3376004+08:00</CreatedDate>
- <Detail>Do Something 1</Detail>
- <Title>Task1</Title>
- </Task>
- <Task>
- <CreatedDate>2011-03-09T21:51:13.3376004+08:00</CreatedDate>
- <Detail>Do Something 2</Detail>
- <Title>Task2</Title>
- </Task>
- <Task>
- <CreatedDate>2011-03-09T21:51:13.3376004+08:00</CreatedDate>
- <Detail>Do Something 3</Detail>
- <Title>Task3</Title>
- </Task>
- <Task>
- <CreatedDate>2011-03-09T21:51:13.3376004+08:00</CreatedDate>
- <Detail>Do Something 4</Detail>
- <Title>Task4</Title>
- </Task>
- <Task>
- <CreatedDate>2011-03-09T21:51:13.3376004+08:00</CreatedDate>
- <Detail>Do Something 5</Detail>
- <Title>Task5</Title>
- </Task>
- </ArrayOfTask>
客户端的调用利用System.Net.WebClient也很容易:
- var client = new WebClient();
- this.txtResponse.Text = client.DownloadString(url);
Json的返回结果: [{"CreatedDate":"//Date(1299687080328+0800)//","Detail":"Do Something 1","Title":"Task1"},{"CreatedDate":"//Date(1299687080328+0800)//","Detail":"Do Something 2","Title":"Task2"},{"CreatedDate":"//Date(1299687080328+0800)//","Detail":"Do Something 3","Title":"Task3"},{"CreatedDate":"//Date(1299687080328+0800)//","Detail":"Do Something 4","Title":"Task4"},{"CreatedDate":"//Date(1299687080328+0800)//","Detail":"Do Something 5","Title":"Task5"}]
再来看看利用jQuery如何调用这个服务:
- <mce:script type="text/javascript" language="JavaScript"><!--
- $(document).ready(function () {
- $("#btnGet").click(function () {
- var url = $("#txtUrl").val();
- $.get(url, function (data) {
- for (var i = 0; i < data.length; i++)
- $("#divResponse").append("<li>" +
- data[i].Title + " - " +
- data[i].Detail + "</li>");
- });
- });
- });
- // --></mce:script>