相關連接html
http://www.cnblogs.com/iamlilinfeng/p/4083827.htmlweb
http://www.cnblogs.com/iamlilinfeng/archive/2012/10/01/2706353.html瀏覽器
一、項目目錄安全
主目錄app
服務庫目錄ide
三種宿主目錄測試
兩種客戶端訪問方式網站
代碼見StudyNoteOfCsharp項目。this
二、WCF開發步驟url
2.一、定義和現實服務協定,在WcfServiceLibrary1服務庫項目裏
namespace WcfServiceLibrary1 { // 注意: 使用「重構」菜單上的「重命名」命令,能夠同時更改代碼和配置文件中的接口名「IService1」。 [ServiceContract] public interface IService1 { [OperationContract] int Add(int a, int b); [OperationContract] int Multiply(int a, int b); } }
namespace WcfServiceLibrary1 { // 注意: 使用「重構」菜單上的「重命名」命令,能夠同時更改代碼和配置文件中的類名「Service1」。 public class Service1 : IService1 { int IService1.Add(int a, int b) { return a + b; } int IService1.Multiply(int a, int b) { return a * b; } } }
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <compilation debug="true" /> </system.web> <!-- 部署服務庫項目時,必須將配置文件的內容添加到 主機的 app.config 文件中。System.Configuration 不支持庫的配置文件。--> <system.serviceModel> <services> <service name="WcfServiceLibrary1.Service1"> <host> <baseAddresses> <add baseAddress = "http://localhost:8733/Design_Time_Addresses/WcfServiceLibrary1/Service1/" /> </baseAddresses> </host> <!-- Service Endpoints --> <!-- 除非徹底限定,不然地址將與上面提供的基址相關 --> <endpoint address="" binding="basicHttpBinding" contract="WcfServiceLibrary1.IService1"> <!-- 部署時,應刪除或替換下列標識元素,以反映 用來運行所部署服務的標識。刪除以後,WCF 將 自動推斷相應標識。 --> <identity> <dns value="localhost"/> </identity> </endpoint> <!-- Metadata Endpoints --> <!-- 元數據交換終結點供相應的服務用於向客戶端作自我介紹。 --> <!-- 此終結點不使用安全綁定,應在部署前確保其安全或將其刪除--> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior> <!-- 爲避免泄漏元數據信息, 請在部署前將如下值設置爲 false --> <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/> <!-- 要接收故障異常詳細信息以進行調試, 請將如下值設置爲 true。在部署前設置爲 false 以免泄漏異常信息--> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
此項目裏調用wcf服務沒有用到上面app.config裏的配置,因此用處不大
2.二、將wcf服務寄宿到winform程序、console控制檯程序、或是web程序裏
寄宿到winform程序裏
winform項目app.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <!--下面是加上去的--> <system.serviceModel> <services> <service name="WcfServiceLibrary1.Service1"> <host> <baseAddresses> <add baseAddress="http://localhost:8081/Service1"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="WcfServiceLibrary1.IService1"></endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="False"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
winform界面
代碼以下
namespace WcfServiceWinformHost { public partial class Form1 : Form { //host的地址和service在app.config裏設置了 ServiceHost host = new ServiceHost(typeof(WcfServiceLibrary1.Service1)); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.Text = "wcf服務監聽已經開啓"; host.Open(); } private void button2_Click(object sender, EventArgs e) { host.Close(); this.Text = "wcf服務監聽已經中止"; } } }
但「開始監聽」時,在瀏覽器裏輸入http://localhost:8081/Service1會看到wcf服務已經啓動,客戶端程序引用http://localhost:8081/Service1地址的服務就能夠。
寄宿到console控制檯
app.config配置以下,但配置是無效的,在Program.cs程序裏沒有用app.config裏的配置
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IService1" /> </wsHttpBinding> </bindings> <client> <endpoint address="http://localhost:8081/Service1" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1" contract="ServiceWinformReference1.IService1" name="WSHttpBinding_IService1"> <identity> <userPrincipalName value="SHENGYU\Administrator" /> </identity> </endpoint> </client> </system.serviceModel> </configuration>
主程序代碼以下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ServiceModel; using System.ServiceModel.Description; using WcfServiceLibrary1; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // Step 1 Create a URI to serve as the base address. Uri baseAddress = new Uri("http://localhost:8733/WcfServiceLibrary1/Service1/"); // Step 2 Create a ServiceHost instance ServiceHost selfHost = new ServiceHost(typeof(Service1), baseAddress); try { // Step 3 Add a service endpoint. selfHost.AddServiceEndpoint(typeof(IService1), new WSHttpBinding(), "Service1"); // Step 4 Enable metadata exchange. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); // Step 5 Start the service. selfHost.Open(); Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); // Close the ServiceHostBase to shutdown the service. selfHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("An exception occurred: {0}", ce.Message); selfHost.Abort(); } } } }
能夠看到,宿主程序將wcf服務發佈到了http://localhost:8733/WcfServiceLibrary1/Service1/而不是app.config裏的http://localhost:8081/Service1,客戶端程序要引用 http://localhost:8733/WcfServiceLibrary1/Service1/就能訪問服務
寄宿到web網站上,wcf將寄宿到iis上
此時服務能夠寫在wcf服務應用程序裏
web.config配置以下
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5"/> </system.web> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <!-- 爲避免泄漏元數據信息,請在部署前將如下值設置爲 false --> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> <!-- 要接收故障異常詳細信息以進行調試,請將如下值設置爲 true。在部署前設置爲 false 以免泄漏異常信息 --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> <protocolMapping> <add binding="basicHttpsBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <!-- 若要在調試過程當中瀏覽 Web 應用程序根目錄,請將下面的值設置爲 True。 在部署以前將該值設置爲 False 可避免泄露 Web 應用程序文件夾信息。 --> <directoryBrowse enabled="true"/> </system.webServer> </configuration>
定義和現實服務協定
namespace WcfServiceWebHost { // 注意: 使用「重構」菜單上的「重命名」命令,能夠同時更改代碼和配置文件中的接口名「IService1」。 [ServiceContract] public interface IService1 { [OperationContract] int Subtract(int a, int b); } }
namespace WcfServiceWebHost { // 注意: 使用「重構」菜單上的「重命名」命令,能夠同時更改代碼、svc 和配置文件中的類名「Service1」。 // 注意: 爲了啓動 WCF 測試客戶端以測試此服務,請在解決方案資源管理器中選擇 Service1.svc 或 Service1.svc.cs,而後開始調試。 public class Service1 : IService1 { public int Subtract(int a, int b) { return a - b; } } }
web運行後的地址爲:http://localhost:7234/Service1.svc,在客戶端調用時只要引用此地址上的服務就可
三、客戶端調用
console控制檯客戶端調用console控制檯服務宿主程序裏的wcf服務
在console控制檯客戶端引用服務,服務地址是http://localhost:8733/WcfServiceLibrary1/Service1/
console控制檯客戶端程序代碼以下:
namespace WcfServiceConsoleClient { class Program { static void Main(string[] args) { ServiceWcfServiceConsoleHostReference1.Service1Client client = new ServiceWcfServiceConsoleHostReference1.Service1Client(); do { var a = int.Parse(Console.ReadLine()); var b = int.Parse(Console.ReadLine()); var result = client.Multiply(a, b); Console.WriteLine("Multiply({0},{1}) = {2}", a, b, result); } while (Console.ReadLine() != "exit"); client.Close(); } } }
運行console控制檯宿主程序WcfServiceConsoleHost.exe
運行console控制檯客戶端程序WcfServiceConsoleClient.exe
console控制檯客戶端調用winform服務宿主程序裏的wcf服務
在console控制檯客戶端引用服務,服務地址是http://localhost:8081/Service1,即winform宿主程序app.config裏配置的地址(其實地址也能夠像上面console控制檯宿主上樣寫在程序裏而不寫在app.config裏)
console控制檯客戶端代碼以下:
namespace WcfServiceConsoleClient { class Program { static void Main(string[] args) { ServiceWcfServiceWinformHostReference1.Service1Client client = new ServiceWcfServiceWinformHostReference1.Service1Client(); do { var a = int.Parse(Console.ReadLine()); var b = int.Parse(Console.ReadLine()); var result = client.Add(a, b); Console.WriteLine("Add({0},{1}) = {2}", a, b, result); } while (Console.ReadLine() != "exit"); client.Close(); } } }
運行winform宿主程序,啓動服務
運行console控制檯客戶端程序WcfServiceConsoleClient.exe
console控制檯客戶端調用web服務宿主程序裏的wcf服務
在console控制檯上引用web服務宿主端http://localhost:7234/Service1.svc的服務
確保web端開啓
console控制檯客戶端代碼以下:
namespace WcfServiceConsoleClient { class Program { static void Main(string[] args) { ServiceWcfServiceWebHostReference1.Service1Client client = new ServiceWcfServiceWebHostReference1.Service1Client(); do { var a = int.Parse(Console.ReadLine()); var b = int.Parse(Console.ReadLine()); var result = client.Subtract(a, b); Console.WriteLine("Subtract({0},{1}) = {2}", a, b, result); } while (Console.ReadLine() != "exit"); client.Close(); } } }
運行console控制檯客戶端程序WcfServiceConsoleClient.exe
winform客戶端調用winform服務端的wcf服務
winform客戶端代碼和界面以下
namespace WcfServiceWinformClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //ServiceWinformHostReference1引用的是WcfServiceWinformHost項目裏app.config裏baseAddress的地址 ServiceWinformHostReference1.Service1Client client = new ServiceWinformHostReference1.Service1Client(); textBox3.Text=client.Add(int.Parse(textBox1.Text), int.Parse(textBox2.Text)).ToString(); } private void button2_Click(object sender, EventArgs e) { ServiceWinformHostReference1.Service1Client client = new ServiceWinformHostReference1.Service1Client(); textBox3.Text = client.Multiply(int.Parse(textBox1.Text), int.Parse(textBox2.Text)).ToString(); } } }
運行客戶端,調用wcf的加法和乘法方法界面以下
總結:wcf步驟爲
一、寫服務接口和實現服務
二、寫宿主程序,能夠是console控制檯、winform、web等等應用程序,並調用服務類,配置好wcf,能夠用app.config或是web.config來配置,也能夠寫在程序裏,記錄好配置後的服務url地址
三、啓用宿主程序,在瀏覽器上確保服務url地址能訪問
四、寫客戶端程序,程序引用宿主的服務url地址,調用服務裏的方法
宿主程序在配置wcf時,可能用如下的代碼方式
Uri baseAddress = new Uri("http://localhost:8733/WcfServiceLibrary1/Service1/"); // Step 2 Create a ServiceHost instance ServiceHost selfHost = new ServiceHost(typeof(Service1), baseAddress);
baseAddress用來設置服務的地址,ServiceHost類將地址和服務類關聯起來
也能夠用config配置文件來配置
<system.serviceModel> <services> <service name="WcfServiceLibrary1.Service1"> <host> <baseAddresses> <add baseAddress="http://localhost:8081/Service1"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="WcfServiceLibrary1.IService1"></endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="False"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
而後在程序裏直接調用:
//host的地址和service在app.config裏設置了 ServiceHost host = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
認識wcf中的「A\B\C",A指address,就是配置文件裏baseaddress的地址,說明去哪裏訪問服務,B指binding,說明能用什麼方式去訪問,如wsHttpBinding,C指Contract描述了Service能提供的各類服務。Contract有四種,包括Service Contract, Data Contract, Fault Contract和Message Contract