本文譯自Walkthrough on creating WCF 4.0 Service and Hosting in IIS 7.5
最近在學習WCF的時候。寄宿IIS7.5這部分總是搞不定。搜了很長時間。發現也是很多文章也是人雲亦雲。根本通不過。於是組合了一下關鍵字,搜了一下英文的文章。總算是搞定了。
目標
本文將會一步步教給你
- 怎么樣創建一個基本的 WCF 4.0 服務?
- 怎么樣把WCF服務寄宿在IIS 7.5?
- 客戶端如何測試服務可用
創建WCF服務
創建WCF服務,打開VS,選擇新工程,然后從WCF的標簽頁里,選擇WCF服務應用程序,來創建一個新的WCF服務。
在IService1 .cs 和Service1.svc.cs中刪除WCF自己添加的默認的代碼。
a. 因此刪除了數據契約
b. 修改服務契約如下. 僅僅寫一個方法契約返回一個字符串
IService1.cs
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.ServiceModel.Web;
usingSystem.Text;
namespaceWcfService5
{
[ServiceContract]
publicinterfaceIService1
{
[OperationContract]
stringGetMessage();
}
}
Service1.svc.cs
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Runtime.Serialization; usingSystem.ServiceModel; usingSystem.ServiceModel.Web; usingSystem.Text; namespaceWcfService5 { publicclassService1:IService1 { publicstringGetMessage() { return"Hello From WCF Service "; } } }
Web.Config
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true"targetFramework="4.0" /> </system.web> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
寄宿WCF服務在IIS7.5中
打開IIS
a. 使用管理員權限打開命令行. 點擊開始->運行 輸入“inetmgr”打開 IIS .
然后你就會到下面這個地方。
b. 在“網站”上右擊,點擊“添加新網站”
c. 然后就打開了新窗口
網站名字隨便給。. 我給了個叫做 HostedWcfService的名字
然后點擊選擇,在應用程序池選擇 ASP.Net v4.0,(ps:如果沒有的話是IIS沒裝全)
現在在物理路徑這里,我們需要把服務的物理路徑填上,為了知道這個物理路徑,我們在VS里,資源管理視圖的的我們的WCF工程上點擊右鍵,選擇在windows資源管理器打開。然后從資源管理器的地址欄把那個地址復制下來。或者你如果很清楚的話自己在瀏覽里找到就行了
然后再綁定這里我們選擇 HTTP. 給個任意的端口數字. 我寫個4567
主機名就不要亂填了,. 留空即可
立即開始網站的選項也選上。
點擊ok。
d. 然后以管理員權限打開Visual Studio 命令提示(2010).
輸入如下命令
aspnet_regiis.exe /iru
一會會告訴你安裝完成 ASP.Net 4.0(注意,有些人可能在前面的應用程序池那塊沒有.net 4 的選項,可以先把這一步做了再去執行前一步。)
e. 然后去 IIS, 會發現網站已經好了
發布WCF服務
回到我們的VS中的 WCF 服務項目. 右擊選擇發布。
On clicking of publish a window will come.
給一個服務的URL,你隨意給,只要保證名字唯一確定即可,服務名以svc結尾就好
把前面創建的網站的名字 HostedWcfService 寫到下面.
證書這塊就不要了
Now click on Publish.
點擊發布后提示發布成功
在IIS中瀏覽服務
打開IIS,然后在 HostedWcfService.網站上點擊右鍵 ->管理網站->瀏覽
當你點擊瀏覽。會出現下面的情況
會得到上面的錯誤。但是這都不是事,在URL后面加上 Service1.svc 就打開了
http://localhost:4567/Service1.svc
在瀏覽器里你可以看到服務已經正常運行了
現在你已經成功的創建了 WCF 4.0 服務並且寄宿在了 IIS 7.5中
在客戶端測試WCF服務
a. 創建一個控制台工程
b. 右鍵點擊,添加服務引用
c. 給出服務的地址,點擊前往,(或者直接點擊發現)選中服務,點擊確定
d. 如下使用服務
Program.cs
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingConsoleApplication1.ServiceReference1; namespaceConsoleApplication1 { classProgram { staticvoidMain(string[]args) { Service1Client proxy=newService1Client(); Console.WriteLine(proxy.GetMessage()); Console.Read(); } } }
輸出結果。
原文鏈接:http://leaver.me/archives/1245.html