WCF快速搭建Demo
ps:本Demo只是演示如何快速建立WCF
1.首先完成IBLL、BLL、Model層的搭建,由於數據訪問層不是重點,WCF搭建才是主要內容,所以本Demo略去數據訪問層。
新建BLL類庫項目,添加UserInfo類如下:
1 namespace Model 2 { 3 [DataContract] 4 public class UserInfo 5 { 6 [DataMember] 7 public int Id { get; set; } 8 [DataMember] 9 public string Name { get; set; } 10 } 11 }
當實體對象作為網絡傳輸時需要被序列化,所以注意以下幾點:
1.不給任何標記將會做XML映射,所有公有屬性/字段都會被序列化
2.[Serializable]標記會將所有可讀寫字段序列化
3.[DataContract]和[DataMember]聯合使用來標記被序列化的字段
接下來,新建IBLL類庫項目,添加IUserInfoService類作為接口契約,代碼如下:
1 namespace IBLL 2 { 3 [ServiceContract] 4 public interface IUserInfoService 5 { 6 [OperationContract] 7 UserInfo GetUser(int id); 8 } 9 }
ps:需要操作的方法一定要記得打上標簽!
同樣,新建BLL類庫項目,添加UserInfoService類,代碼如下(只為測試WCF搭建):
1 namespace BLL 2 { 3 public class UserInfoService:IUserInfoService 4 { 5 public UserInfo GetUser(int id) 6 { 7 return new UserInfo() { Id = id, Name = "test" }; 8 } 9 } 10 }
2.搭建WCFHost(宿主)
新建一個控制台項目,在配置文件app.config中的configuration節點下添加:
<system.serviceModel> <services> <service name="BLL.UserInfoService" behaviorConfiguration="behaviorConfiguration"> <host> <baseAddresses> <add baseAddress="http://localhost:8000/"/> </baseAddresses> </host> <endpoint address="" binding="basicHttpBinding" contract="IBLL.IUserInfoService"></endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior name="behaviorConfiguration"> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
注意以下幾點:
1.因為是本地測試,所以baseAddress填寫了本地的地址,這個可以根據實際修改。
2.service節點的name屬性要修改為BLL層具體服務類的“命名空間+類名”。
3.endpoint節點的contract屬性要修改為IBLL層具體服務類接口的“命名空間+接口名”。
主程序代碼中添加:
1 using (ServiceHost host = new ServiceHost(typeof(UserInfoService))) 2 { 3 host.Open(); 4 Console.WriteLine("服務已啟動,按任意鍵中止..."); 5 Console.ReadKey(); 6 host.Close(); 7 }
ps:typeof()中換成要調用的服務類。
在項目上右鍵選擇“在文件資源管理器中打開文件夾”,找到可執行程序WCFService.exe,右鍵選擇“以管理員身份運行”。
3.最后一步,就是來測試我們的WCF服務是否搭建成功了,新建一個winform窗體項目WCFClient,在項目右鍵,添加服務引用,在地址欄輸入 http://localhost:8000/ (配置文件中填寫的baseAddress)。在該程序中調用剛剛搭建好的WCF服務:
1 UserInfoServiceClient client = new UserInfoServiceClient(); 2 UserInfo u = client.GetUser(5); 3 MessageBox.Show(u.Id + "-" + u.Name);
運行后,彈出消息,表示WCF服務搭建成功!