介紹
WCF(Windows Communication Foundation) - Web編程模型:使用WCF創建REST服務,使用asp.net ajax調用WCF服務
·System.ServiceModel.Activation.WebServiceHostFactory - 用於承載使用 WCF Web 編程模型的服務
·System.ServiceModel.Activation.WebScriptServiceHostFactory - 能夠向服務中自動添加 ASP.NET AJAX 終結點而無需進行配置
示例(使用WCF創建REST服務)
1、服務
User.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.Runtime.Serialization; namespace WCF.ServiceLib.Web { /**//// <summary> /// User實體類 /// </summary> [DataContract] public class User { /**//// <summary> /// 用戶名 /// </summary> [DataMember(Order = 0)] public string Name { get; set; } /**//// <summary> /// 生日 /// </summary> [DataMember(Order = 1)] public DateTime DayOfbirth { get; set; } } }
IREST.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.ServiceModel.Web; namespace WCF.ServiceLib.Web { /**//// <summary> /// 演示REST(Representational State Transfer)的接口 /// </summary> /// <remarks> /// HTTP方法中: /// PUT相當於Create /// GET相當於Read /// POST相當於Update /// DELETE相當於Delete /// </remarks> [ServiceContract] public interface IREST { /**//// <summary> /// 創建用戶 /// </summary> /// <param name="name">用戶名</param> /// <param name="dayOfbirth">生日</param> /// <remarks> /// WebInvoke - 指示服務操作在邏輯上就是調用操作,而且可由 Web 編程模型調用 /// UriTemplate - 用於服務操作的統一資源標識符 (URI) 模板。URI模板可以將一個 URI 或一組 URI 映射到服務操作。有關 URI 模板的更多信息,請參見 UriTemplate 和 UriTemplateTable /// Method - 與操作關聯的協議方法,默認為 POST /// ResponseFormat - 指定從服務操作發出的響應的格式。Xml 或 Json /// </remarks> [OperationContract] [WebInvoke( UriTemplate = "User/{name}/{dayOfbirth}", Method = "PUT", ResponseFormat = WebMessageFormat.Json)] User CreateUser(string name, string dayOfbirth); /**//// <summary> /// 獲取用戶信息 /// </summary> /// <param name="name">用戶名</param> /// <remarks> /// WebGet - 指示服務操作在邏輯上就是檢索操作,而且可由 Web 編程模型調用 /// </remarks> [OperationContract] [WebGet( UriTemplate = "User/{name}", ResponseFormat = WebMessageFormat.Json)] User GetUser(string name); /**//// <summary> /// 更新用戶信息 /// </summary> /// <param name="name">用戶名</param> /// <param name="dayOfbirth">生日</param> /// <returns></returns> [OperationContract] [WebInvoke(UriTemplate = "User/{name}/{dayOfbirth}", Method = "POST", ResponseFormat = WebMessageFormat.Json)] bool UpdateUser(string name, string dayOfbirth); /**//// <summary> /// 刪除用戶信息 /// </summary> /// <param name="name">用戶名</param> /// <returns></returns> [OperationContract] [WebInvoke( UriTemplate = "User/{name}", Method = "DELETE", ResponseFormat = WebMessageFormat.Json)] bool DeleteUser(string name); } }
REST.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace WCF.ServiceLib.Web { /**//// <summary> /// 演示REST(Representational State Transfer)的類 /// </summary> public class REST : IREST { public User CreateUser(string name, string dayOfbirth) { return new User { Name = name, DayOfbirth = DateTime.Parse(dayOfbirth) }; } public User GetUser(string name) { return new User { Name = name, DayOfbirth = new DateTime(1980, 2, 14) }; } public bool UpdateUser(string name, string dayOfbirth) { return true; } public bool DeleteUser(string name) { return true; } } }
2、宿主
REST.svc
<%@ ServiceHost Language="C#" Debug="true" Service="WCF.ServiceLib.Web.REST" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
注:System.ServiceModel.Activation.WebServiceHostFactory - 用於承載使用 WCF Web 編程模型的服務
Web.config
<?xml version="1.0"?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="WebBehavior"> <!--httpGetEnabled - 指示是否發布服務元數據以便使用 HTTP/GET 請求進行檢索,如果發布 WSDL,則為 true,否則為 false,默認值為 false--> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="RESTBehavior"> <!--webHttp - 啟用 WCF 服務的 Web 編程模型--> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <services> <!--name - 提供服務的類名--> <!--behaviorConfiguration - 指定相關的服務行為配置--> <service name="WCF.ServiceLib.Web.REST" behaviorConfiguration="WebBehavior"> <!--address - 服務地址--> <!--binding - 通信方式--> <!--contract - 服務契約--> <!--behaviorConfiguration - 指定相關的端點行為配置--> <endpoint address="" binding="webHttpBinding" contract="WCF.ServiceLib.Web.IREST" behaviorConfiguration="RESTBehavior" /> </service> </services> </system.serviceModel> </configuration>
3、客戶端
REST.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="REST.aspx.cs" Inherits="Web_REST" Title="WCF創建REST" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> <asp:Label ID="lblMsg" runat="server" /> </asp:Content>
REST.aspx.cs
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Net; public partial class Web_REST : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { var client = new WebClient(); var create = client.UploadString("http://localhost:3502/ServiceHost/Web/REST.svc/User/webabcd/1980-2-14", "PUT", string.Empty); var read = client.DownloadString("http://localhost:3502/ServiceHost/Web/REST.svc/User/webabcd"); var update = client.UploadString("http://localhost:3502/ServiceHost/Web/REST.svc/User/webabcd/1980-2-14", "POST", string.Empty); var delete = client.UploadString("http://localhost:3502/ServiceHost/Web/REST.svc/User/webabcd", "DELETE", string.Empty); lblMsg.Text = string.Format("{0}<br />{1}<br />{2}<br />{3}", create, read, update, delete); } }
運行結果:
{"Name":"webabcd","DayOfbirth":"\/Date(319305600000+0800)\/"}
{"Name":"webabcd","DayOfbirth":"\/Date(319305600000+0800)\/"}
true
true
示例(使用asp.net ajax調用WCF服務)
1、服務
User.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.Runtime.Serialization; namespace WCF.ServiceLib.Web { /**//// <summary> /// User實體類 /// </summary> [DataContract] public class User { /**//// <summary> /// 用戶名 /// </summary> [DataMember(Order = 0)] public string Name { get; set; } /**//// <summary> /// 生日 /// </summary> [DataMember(Order = 1)] public DateTime DayOfbirth { get; set; } } }
IAJAX.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace WCF.ServiceLib.Web { /**//// <summary> /// 演示AJAX的接口 /// </summary> [ServiceContract(Namespace = "WCF")] public interface IAJAX { /**//// <summary> /// 獲取用戶 /// </summary> /// <param name="name">用戶名</param> /// <returns></returns> [OperationContract] User GetUser(string name); } }
AJAX.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.ServiceModel.Activation; namespace WCF.ServiceLib.Web { /**//// <summary> /// 演示AJAX的類 /// </summary> /// <remarks> /// ASP.NET 兼容性模型: /// 如果在負載平衡或者甚至 Web 園的環境中承載 WCF 服務,並且在該環境中後續的會話請求可以被此環境內的不同宿主或進程處理,則需要對會話狀態進行進程外持久存儲。最新的 WCF 不支持會話狀態的持久存儲。相反,WCF 將它的所有會話狀態存儲在內存中。如果在 IIS 中承載 WCF 服務,最後可以使用回收方案。 /// WCF 依賴於會話狀態的 ASP.NET 實現,而不是為會話全部再次建立持久存儲。此方式有一個嚴重的限制:使服務僅限於 HTTP /// ASP.NET 會話狀態不是受 ASP.NET 兼容性模式支持的唯一功能。它還支持諸如 HttpContext、globalization 和模擬等功能,就像用於 ASP.NET Web 服務 (ASMX) 一樣 /// </remarks> /// [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class AJAX : IAJAX { public User GetUser(string name) { return new User { Name = name, DayOfbirth = new DateTime(1980, 2, 14) }; } } }
2、宿主
AJAX.svc
<%@ ServiceHost Language="C#" Debug="true" Service="WCF.ServiceLib.Web.AJAX" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>
注:System.ServiceModel.Activation.WebScriptServiceHostFactory - 能夠向服務中自動添加 ASP.NET AJAX 終結點而無需進行配置
Web.config
<?xml version="1.0"?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="WebBehavior"> <!--httpGetEnabled - 指示是否發布服務元數據以便使用 HTTP/GET 請求進行檢索,如果發布 WSDL,則為 true,否則為 false,默認值為 false--> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="AJAXBehavior"> <!--enableWebScript - 啟用 WCF 服務的 腳本 編程模型--> <enableWebScript /> </behavior> </endpointBehaviors> </behaviors> <services> <!--name - 提供服務的類名--> <!--behaviorConfiguration - 指定相關的服務行為配置--> <service name="WCF.ServiceLib.Web.AJAX" behaviorConfiguration="WebBehavior"> <!--address - 服務地址--> <!--binding - 通信方式--> <!--contract - 服務契約--> <!--behaviorConfiguration - 指定相關的端點行為配置--> <endpoint address="" binding="webHttpBinding" contract="WCF.ServiceLib.Web.IAJAX" behaviorConfiguration="AJAXBehavior" /> </service> </services> </system.serviceModel> </configuration>
3、客戶端
Demo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Demo.aspx.cs" Inherits="Demo" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>AJAX調用WCF</title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="Service/AJAX.svc" /> </Services> </asp:ScriptManager> <asp:Label ID="lblMsg" runat="server" /> <script type="text/javascript"> function pageLoad() { var proxy = new WCF.IAJAX(); proxy.GetUser("webabcd", onSuccess); } function onSuccess(result) { $get('<%= lblMsg.ClientID %>').innerHTML = String.format("姓名:{0}<br />生日:{1}", result.Name, result.DayOfbirth.format("yyyy-MM-dd")); } </script> </form> </body> </html>
運行結果:
姓名:webabcd
生日:1980-02-14
OK