构建和测试 WCF RESTful 服务






4.71/5 (9投票s)
构建和测试 WCF RESTful 服务
引言
以下文章将介绍如何使用 WCF 框架构建 RESTful 服务。我还要实现的目标是拥有多个终结点。1. RESTful 终结点
2. TCP/IP 终结点。
通过这样做,我们可以尝试满足不同类型的客户端。RESTful 服务可以被所有类型的客户端访问,而 TCP/IP 可以被 .Net 客户端访问。正如你们许多人可能已经知道的,TCP/IP 最适合提供更好的性能。文章的最后,我还会介绍如何使用 fiddler 工具测试您的 REST 服务。什么是 REST
• REST 代表 Representational State Transfer (表述性状态转移)
• REST 是通过通用接口访问资源。
• REST URI:Uniform Resource Identifier (统一资源标识符) - 这是在网络上标识资源的唯一方式。
• 您还可以参考以下链接了解所有 REST 术语。
http://msdn.microsoft.com/en-us/library/dd203052.aspx为实现上述目标所采取的步骤
添加服务
• 向解决方案添加一个类库项目
• 使用 IService 接口和 Service Contract 实现服务。
• 服务将与 Northwind 数据库交互。
托管服务
• 添加一个控制台应用程序并
• 使用 app.config 配置 TCP/IP 和 RESTful 服务。
• 在控制台应用程序中托管服务。
测试服务
• 创建一个 Windows 应用程序来消费服务。
1. RESTful 终结点
2. TCP/IP 终结点
• 使用浏览器和 Fiddler 工具测试 RESTful 服务
添加服务
• 创建一个 .Net 解决方案
• 添加一个名为 SampleServices 的类库项目。
• 添加“LINQ to SQL”类,Northwind.dbml。
我想与 Northwind 数据库的 Category 表进行通信。添加 Northwind.dbml 文件后,使用 LINQ 设计器中的服务器资源管理器连接到本地服务器。然后将 Category 表拖放到 LINQ 设计器上。
• 您需要更改 SQL 连接字符串,以指向包含 northwind 数据库的本地服务器。
• 添加 C# 类 IService 和 Service
• 确保您添加了以下引用:System.ServiceModel & System.ServiceModel.Web
• IService 接口代码
[ServiceContract] public interface IService { [OperationContract] [WebInvoke(UriTemplate = "/Category/{categoryID}", Method = "GET")] Category GetCategory(string CategoryID); [OperationContract] [WebInvoke(UriTemplate = "/Category", Method = "GET")] List <category /> GetCategories(); [OperationContract] [WebInvoke(UriTemplate = "/Category/Add", Method = "POST")] bool AddCategory(Category category); }
• Service 代码
public class Service : IService { public Category GetCategory(string categoryID) { NorthwindDataContext context = new NorthwindDataContext(); var category = context.Categories.SingleOrDefault(e => e.CategoryID == Convert.ToInt32(categoryID)); context.Dispose(); return category; } public List <category /> GetCategories() { NorthwindDataContext context = new NorthwindDataContext(); var categories = context.Categories.ToList(); context.Dispose(); return categories; } public bool AddCategory(Category category) { NorthwindDataContext context = new NorthwindDataContext(); context.Categories.InsertOnSubmit(category); context.SubmitChanges(); context.Dispose(); return true; } }
托管服务
• 添加一个控制台应用程序“ServiceHost”
• 确保您添加了对 System.ServiceModel 程序集的引用。
• 添加对 SampleService.dll 的引用
• 配置 app.config 以支持 REST 和 TCP/IP 终结点
<system.serviceModel> <services> <service name="SampleServices.Service" behaviorConfiguration="MYServiceBehavior"> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <endpoint address="net.tcp://:12000/SampleServices/Service" binding="netTcpBinding" bindingConfiguration="TCPBindingDetails" contract="SampleServices.IService" behaviorConfiguration="TCPBehavior"> </endpoint> <endpoint name="webHttpBinding" address="REST" binding="webHttpBinding" behaviorConfiguration="RESTBehavior" contract="SampleServices.IService" /> <host> <baseAddresses> <add baseAddress="<a href="https://:9002/SampleServices/Service/">https://:9002/SampleServices/Service/</a />" /> </baseAddresses> <timeouts closeTimeout="01:20:10" openTimeout="01:20:00" /> </host> </service> </services> <bindings> <netTcpBinding> <binding name="TCPBindingDetails" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="5000000" maxBufferSize="5000000" maxConnections="10" maxReceivedMessageSize="5000000"> <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:30:00" enabled="false" /> <security mode="Transport"> <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" /> <message clientCredentialType="None" /> </security> </binding> </netTcpBinding> </bindings> <behaviors> <endpointBehaviors> <clear /> <behavior name="TCPBehavior"> <dataContractSerializer maxItemsInObjectGraph="6553600" /> </behavior> <behavior name="RESTBehavior"> <dataContractSerializer maxItemsInObjectGraph="6553600" /> <webHttp helpEnabled="true" /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="MYServiceBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel>
注意: helpEnabled="true"
• program.cs 中的托管代码
static void Main(string[] args) { // Create a ServiceHost for the CaseStudyService type. System.ServiceModel.ServiceHost serviceHost = new System.ServiceModel.ServiceHost(typeof(SampleServices.Service)); // Open the ServiceHost to create listeners and start listening for messages. serviceHost.Open(); Console.WriteLine("Services are ready & running."); Console.WriteLine(); Console.ReadLine(); }
测试服务
• 创建一个 Windows 应用程序,“Client”
• 添加对 System.ServiceModel & System.Runtime.Serialization 的引用
• 使用 svcutil.exe 生成代理
• 将代理类添加到客户端应用程序。
• 访问 TCP/IP 终结点的示例代码。
ServiceClient client = new ServiceClient(); var allCategories = client.GetCategories(); MessageBox.Show(allCategories.Count().ToString());
• 访问 REST 服务的示例代码。
WebRequest request = WebRequest.Create("https://:9002/SampleServices/Service/REST/Category/1"); WebResponse ws = request.GetResponse(); Encoding enc = System.Text.Encoding.GetEncoding(1252); StreamReader responseStream = new StreamReader(ws.GetResponseStream()); string response = responseStream.ReadToEnd(); responseStream.Close(); MessageBox.Show(response);
• 您还可以通过浏览器和 Fiddler 工具测试基于 REST 的服务。
• 重要提示:通过启用服务的帮助,您可以了解以下项
o URI
o 方法类型
o 描述
o GET 方法所需的数据格式
o POST 方法的数据格式或请求正文。
您可以通过浏览 https://:9002/SampleServices/Service/REST/help 获取所有这些信息
点击方法将提供示例响应 XML
点击 POST 方法将提供要发送的请求 XML。
使用 RESTful 服务在浏览器中获取所有类别 https://:9002/SampleServices/Service/REST/Category
• 获取 ID = 1 的类别的详细信息,https://:9002/SampleServices/Service/REST/Category/1
• 使用 Fiddler:转到 Fiddler 工具中的请求生成器并键入 URL,选择 GET 方法。然后单击执行按钮。URL:https://:9002/SampleServices/Service/REST/Category/
注意:请确保您正在运行 WCF 主机
• 双击 Web Session 面板中的请求,即可看到响应。
• 您也可以使用 Fiddler 来处理 POST 方法。为了添加一个类别,我们需要使用 URI https://:9002/SampleServices/Service/REST/Category/Add,这是一个 POST 方法。我们可以通过帮助 URL 获取请求 XML。
2147483647 字符串内容 字符串内容 1999-05-31T11:20:00 QmFzZSA2NCBTdHJlYW0=
让我们使用以上格式在 Fiddler 工具中添加一个新类别。删除 CategoryID,因为这是数据库中的自动生成列。在 Fiddler 工具中使用以下格式
新类别 新类别 2012-05-31T11:20:00
• 在方法中选择“POST”。提供 URL
https://:9002/SampleServices/Service/REST/Category/Add在请求头中添加 content-type:application/xml。
在请求正文中添加上述 XML。
• 单击执行并在数据库中检查类别是否已插入。您也可以在浏览器中使用 RESTful 服务进行检查。https://:9002/SampleServices/Service/REST/Category