.NET Magazine國際中文電子雜誌
作 者:許薰尹
審 稿:張智凱
文章編號: N190220401
出刊日期: 2019/2/6
因為有太多的舊專案使用到Web服務與WCF服務,因此若考慮使用ASP.NET Core的技術來全面取代舊系統看來不是一蹴可及的事,恐有一段新舊技術並存同時運作的時期,因此目前最常被討論到的問題是,如何在ASP.NET Core MVC的專案之中叫用Web服務與WCF服務。
Visual Studio 2017開發工具新增一個「Microsoft WCF Web Service Reference Provider」工具,可以讓你在ASP.NET Core MVC專案中,利用圖型介面,根據方案中,或遠端網路位置,或從WSDL檔案來取得服務相關資訊,進而產生叫用服務的代理程式碼,讓我們可以很容易的使用這些傳統的服務。以下將以Step-by-Step步驟說明該如何利用Visual Studio 2017新增一個Web服務與WCF服務,並在ASP.NET Core MVC的專案之中叫用它們。
建立Web服務
從Visual Studio 2017開發工具的主選單點選「File」-「New」-「Project」項目,在「New Project」對話盒中,選取左方「Installed」清單 -「Visual C#」程式語言,從「Web」分類中,選取「Previous Versions」-「ASP.NET Empty Web Site」。適當設定「Name」與「Location」,確認視窗下方.NET Framework的目標版本為「.NET Framework 4.6.1」以上,然後按下「OK」按鈕,請參考下圖所示:

圖 1:建立「ASP.NET Empty Web Site」。
在網站之中加入一個WebService.asmx檔案。從「Solution Explorer」視窗 - 網站名稱(WSSite)上方,按滑鼠右鍵,從快捷選單選擇「Add」- 「Add New Item」項目,從「Add New Item」對話盒中,選取「Visual C#」分類下的「Web Service」項目,然後在下方將「Name」設定為「WebService.asmx」,勾選「Place code in separate file」核取方塊,最後按下「Add」按鈕,請參考下圖所示:

圖 2:加入Web服務。
在WebService.cs檔案中,預設會包含一個「HelloWorld」方法,程式碼參考如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService( Namespace = "http://tempuri.org/" )]
[WebServiceBinding( ConformsTo = WsiProfiles.BasicProfile1_1 )]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService( ) {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld( ) {
return "Hello World";
}
}
修改預設的「HelloWorld」方法,變更名稱為「Add」方法,讓方法回傳int型別。「Add」方法加入「x」、「y」兩個「int」型別參數,並將兩參數相加的結果回傳,程式碼參考如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService( Namespace = "http://tempuri.org/" )]
[WebServiceBinding( ConformsTo = WsiProfiles.BasicProfile1_1 )]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService( ) {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public int Add( int x , int y ) {
return x + y;
}
}
選取Visual Studio 開發工具「Build」-「Build Solution」項目編譯目前的專案,確認程式碼能正確編譯。
使用瀏覽器執行Web Service測試。在「Solution Explorer」視窗,點選「WebService.asmx」檔案,然後按滑鼠右鍵,從快捷選單中選取「View In Browser」項目。得到的執行結果如下圖所示:

圖 3:測試Web服務。
使用滑鼠點選開放出來的服務功能「Add」方法,並且在參數的地方輸入兩個數值,再按下「Invoke」按鈕執行測試,請參考下圖所示:

圖 4:輸入測試資料。
叫用Web Service成功之後,將會將訊息回傳回來,顯示在網頁上,請參考下圖所示:

圖 5:Web服務執行結果。
加入ASP.NET Core MVC專案
從「Solution Explorer」視窗 – Solution檔案上方,按滑鼠右鍵,從快捷選單選擇「Add」- 「New Project」項目,請參考下圖所示:

圖 6:加入新專案。
在「New Project」對話盒中,選取左方「Installed」清單-「Visual C#」程式語言,從「.NET Core」分類中,選取「ASP.NET Core Web Application」。設定專案名稱,設定專案存放路徑,然後按下「OK」鍵,請參考下圖所示:

圖 7:建立「ASP.NET Core Web Application」專案。
在「New ASP.NET Core Web Application」對話盒中,確認左上方的清單選取「.NET Core」,右上方的清單ASP.NET Core版本為「ASP.NET Core 2.1」,選取下方的「Web Application ( Model – View – Controller) 」樣版專案,清除勾選下方的「Enable Docker Support」核取方塊,確定右方的「Authentication」項目設定為「No Authentication」,然後按下「OK」按鈕建立專案,請參考下圖所示:

圖 8:選取「Web Application ( Model – View – Controller) 」樣版專案。
產生叫用Web Service的代理程式
從「Solution Explorer」視窗 – ASP.NET Core MVC網站名稱下的「Dependencies」項目,按滑鼠右鍵,從快捷選單選擇「Add Connected Service」項目,請參考下圖所示:

圖 9:選擇「Add Connected Service」項目。
選取「Microsoft WCF Web Service Reference Provider」項目,請參考下圖所示:

圖 10:選取「Microsoft WCF Web Service Reference Provider」項目。
下一步會進入「Configure WCF Web Service Reference」對話盒。若服務存在於目前的方案之中,只要點選「Discover」按鈕,Visual Studio就會自動搜尋目前方案中所有可以使用的服務。若服務存在於遠端位置,那麼只要在文字方塊中輸入服務的URI位置,再按下「Go」按鈕。若擁有服務的WSDL檔案,那麼只要選取「Browse」按鈕,再選取WSDL檔案,就可以得到服務描述資訊。
在目前的步驟點選「Discover」項目,選取「Web Service Soap」可以看到目前可叫用的操作(Operation),按一下「Next」按鈕到下一個畫面,請參考下圖所示:

圖 11:探索方案中的服務。
按一下「Next」按鈕到下一個畫面,以設定「Data Type Options」,請參考下圖所示:

圖 12:設定「Data Type Options」畫面。
按一下「Next」按鈕到下一個畫面,以設定設定「Access Level」,請參考下圖所示:

圖 13:設定「Access Level」。
按一下「Finish」按鈕,工具就會開始搜集服務資訊,並產生代理程式碼,請參考下圖所示:

圖 14:產生代理程式碼。
完成後在「Solution Explorer」視窗,「Connected Services」項目下會產生一個「ServiceReference1」資料夾,其中包含一個「Reference.cs」檔案,其中將包含叫用服務的代理程式碼,請參考下圖所示:

圖 15:產生出Reference.cs程式碼
在控制器叫用Web服務
修改「HomeController」類別的「Index」方法,加入以下程式碼,利用代理程式叫用服務,然後將服務執行結果轉換成字串,直接顯示在網頁中:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreWebMVC.Models;
using ServiceReference1;
namespace CoreWebMVC.Controllers {
public class HomeController : Controller {
public async Task<string> Index( ) {
int x= 10;
int y = 20;
WebServiceSoapClient ws = new WebServiceSoapClient( WebServiceSoapClient.EndpointConfiguration.WebServiceSoap );
var r = await ws.AddAsync( x , y );
return r.ToString();
}
}
}
選取Visual Studio 開發工具「Build」-「Build Solution」項目編譯目前的專案,確認程式碼能正確編譯。
設定多重起始專案
最後,我們要來測試一下服務是否可以正確被叫用,我們需要在Visual Studio設定多重起始專案。在「Solution Explorer」視窗方案名稱上按下滑鼠右鍵選取「Properties」項目 ,設定專案啟動選取「Multiple startup projects」,指定Web服務網站(WSSite)與ASP.NET Core MVC(CoreWebMVC)兩個專案都為起始專案,並利用右方向上、向下箭頭調整專案執行順序,要先執行Web服務網站(WSSite),再執行ASP.NET Core MVC(CoreWebMVC)網站,按下「OK」,請參考下圖所示:

圖 16:設定多重起始專案。
在Visual Studio開發工具,按CTRL+F5同時執行網站,ASP.NET Core MVC網站會顯示出兩數相加的執行結果,請參考下圖所示:

圖 17:叫用Web服務的執行結果。
加入WCF服務專案
在ASP.NET Core MVC專案中叫用WCF服務的步驟和上述叫用Web服務的步驟差不多。我們先在目前的方案中,加入WCF服務專案。從「Solution Explorer」視窗 – Solution檔案上方,按滑鼠右鍵,從快捷選單選擇「Add」- 「New Project」項目。在「Add New Project」對話盒中,選取左方「Installed」清單 -「Visual C#」程式語言,從「Web」分類中,選取「Previous Versions」-「WCF Service」項目。適當設定「Name」與「Location」,確認視窗下方.NET Framework的目標版本為「.NET Framework 4.6.1」以上,然後按下「OK」按鈕,請參考下圖所示:

圖 18:加入WCF服務專案。
預設此範本專案將會把服務裝載在IIS中執行。專案中包含一個「IService.cs」檔案,其中定義一個「IService」 介面套用ServiceContract Attribute代表服務合約:
[ServiceContract]
public interface IService
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
「Service.cs」檔案則包含Service 服務實作的程式碼,參考實作如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
我們以範本專案的程式為例,示範呼叫需傳簡單參數的「GetData」方法。
產生叫用WCF Service的代理程式
從「Solution Explorer」視窗 – ASP.NET Core MVC網站(CoreWebMVC)名稱下的「Connected Services」或「Dependencies」項目,按滑鼠右鍵,從快捷選單選擇「Add Connected Service」項目,請參考下圖所示:

圖 19:選擇「Add Connected Service」項目。
選取「Microsoft WCF Web Service Reference Provider」項目,請參考下圖所示:

圖 20:選取「Microsoft WCF Web Service Reference Provider」項目。
點選「Discover」,Visual Studio就會自動搜尋目前方案中所有可以使用的服務,這次可以看到方案中包含先前的Web服務(WebService.asmx),與新加入的WCF服務(Service.svc)。選取「Service.svc」-「Service」-「IService」可以看到目前可叫用的「GetData」操作(Operation),按一下「Next」按鈕到下一個畫面,請參考下圖所示:
圖 21:探索方案中的服務。
按一下「Next」按鈕到下一個畫面,以設定「Data Type Options」,請參考下圖所示:

圖 22:設定「Data Type Options」畫面。
按一下「Next」按鈕到下一個畫面,以設定設定「Access Level」,請參考下圖所示:

圖 23:設定「Access Level」。
按一下「Finish」按鈕,工具就會開始搜集服務資訊,並產生代理程式碼,請參考下圖所示:

圖 24:產生代理程式碼。
完成後在「Connected Services」下會產生一個「ServiceReference2」資料夾,其中包含一個「Reference.cs」檔案,其中將包含叫用服務的代理程式碼,請參考下圖所示:

圖 25:產生出Reference.cs程式碼。
在控制器叫用WCF服務
修改「HomeController」類別的「Index」方法,加入以下程式碼,利用代理程式叫用服務,然後將服務執行結果轉換成字串,直接顯示在網頁中:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreWebMVC.Models;
using ServiceReference2;
namespace CoreWebMVC.Controllers {
public class HomeController : Controller {
public async Task<string> Index( ) {
int x = 100;
ServiceClient ws = new ServiceClient( );
var r = await ws.GetDataAsync( x );
return r.ToString( );
}
}
}
設定多重起始專案
在「Solution Explorer」視窗方案名稱上按下滑鼠右鍵選取「Properties」項目 ,設定專案啟動選取「Multiple startup projects」,指定WCF服務(WCFService)與ASP.NET Core MVC(CoreWebMVC)兩個專案都為起始專案,並利用右方向上、向下箭頭調整專案執行順序,要先執行WCF服務(WCFService),再執行ASP.NET Core MVC(CoreWebMVC)網站,按下「OK」,請參考下圖所示:

圖 26:設定多重起始專案。
在Visual Studio開發工具,按CTRL+F5同時執行網站,ASP.NET Core MVC網站會顯示出叫用服務的執行結果,請參考下圖所示:

圖 27:叫用WCF服務的執行結果。