Web Service 是分散式、模組化應用程式的關鍵技術,具備自描述、可發現、跨平台互通特性。本文以「美元兌人民幣匯率轉換」為例,示範在 Visual Studio.NET 中使用 C# 建立、部署與測試 Web Service 的完整流程。
傳統分散式技術(DCOM、CORBA、RMI)要求客戶端與伺服器緊密耦合、同質架構,難以跨越防火牆與異構平台。Web Service 採用 HTTP + XML(SOAP)的鬆散耦合架構,任何支援 HTTP 連線的用戶端皆可呼叫,實現真正的跨平台互操作。
WebService1。HelloWorld 範例,撰寫匯率轉換邏輯:using System;
using System.Web.Services;
namespace WebService1
{
public class Service1 : System.Web.Services.WebService
{
public Service1() { InitializeComponent(); }
#region 元件設計工具產生的程式碼
private System.ComponentModel.IContainer components = null;
private void InitializeComponent() { }
protected override void Dispose(bool disposing)
{
if (disposing && components != null) components.Dispose();
base.Dispose(disposing);
}
#endregion
// Web 服務方法
[WebMethod]
public double DollarConvertToRMB(double Dollar)
{
// 實務應用應從資料庫即時取得匯率
return Dollar * 8.15; // 假設固定匯率 1:8.15
}
}
}
關鍵點:
System.Web.Services.WebService。[WebMethod] 屬性即可公開為 Web Service 操作。System.Web.Services 命名空間。C:\Inetpub\wwwroot\WebService1\Service1.asmx)。.asmx 為 ASP.NET Web Service 標準副檔名。https://localhost/WebService1/Service1.asmx 或在 VS.NET 按 Ctrl+F5 執行。[WebMethod] 方法。點選 DollarConvertToRMB,輸入參數 10,按「叫用」。<?xml version="1.0" encoding="utf-8"?>
<double xmlns="https://tempuri.org/">81.5</double>
結果顯示 10 美元成功轉換為 81.5 人民幣。實際應用中,用戶端程式會解析此 XML 並呈現友善介面。
本例展示 Web Service 建立的簡易性:無需 COM/DCOM、無需 Windows 用戶端,純 HTTP + XML 即可實現全球可及的分散式元件。進階應用可整合資料庫即時匯率、加入驗證授權、支援複雜商務邏輯,構建真正的企業級服務導向架構(SOA)。