ASP.NET Web Service (.asmx) 雖屬舊世代技術,但在維護舊系統或需快速對外暴露 SOAP 介面時仍具實用價值。本文帶領從專案建立、方法撰寫、資料庫存取到用戶端呼叫的完整流程。
Service1.asmx 與 Service1.asmx.cs。using System;
using System.Web.Services;
namespace AuthorWebService
{
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
public Service1() { }
// [WebMethod]
// public string HelloWorld() { return "Hello World!"; }
}
}
重點:在公用方法加上 [WebMethod] 屬性即可暴露為 SOAP 操作。
[WebMethod]
public DataSet GetAuthorsExcludeId(string excludeId)
{
string sql = "SELECT au_id, au_fname, au_lname FROM authors WHERE au_id != @id";
string connStr = @"Server=localhost;Database=pubs;User ID=sa;Password=yourPwd;";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@id", excludeId); // 參數化防 SQL Injection
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "author_list");
return ds; // DataSet 可自動序列化為 XML 回傳
}
}
改進說明:
using 區塊確保連線正確釋放。DataSet 而非 DataTable,前者包含結構描述,用戶端反序列化更容易。Service1.asmx 測試頁,點擊方法名稱可輸入參數並送出測試。輸入 https://yourhost/Service1.asmx,VS 產生 Proxy 類別,呼叫如同本地方法:
var proxy = new localhost.Service1();
DataSet ds = proxy.GetAuthorsExcludeId("172-32-1176");
foreach (DataRow row in ds.Tables["author_list"].Rows)
Console.WriteLine($"{row["au_fname"]} {row["au_lname"]}");
string soapEnvelope = @"<?xml version=\"1.0\"?>
<soap:Envelope xmlns:soap=\"https://schemas.xmlsoap.org/soap/envelope/\"
xmlns:xsi=\"https://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"https://www.w3.org/2001/XMLSchema\">
<soap:Body>
<GetAuthorsExcludeId xmlns=\"https://tempuri.org/\">
<excludeId>172-32-1176</excludeId>
</GetAuthorsExcludeId>
</soap:Body>
</soap:Envelope>";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://yourhost/Service1.asmx");
req.Method = "POST";
req.ContentType = "text/xml; charset=utf-8";
req.Headers.Add("SOAPAction", ""https://tempuri.org/GetAuthorsExcludeId"");
using (Stream stm = req.GetRequestStream())
using (StreamWriter sw = new StreamWriter(stm))
sw.Write(soapEnvelope);
using (WebResponse resp = req.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
Console.WriteLine(sr.ReadToEnd());
| 問題 | 說明 |
|---|---|
| 回傳 DataSet 序列化龐大 | 考慮改回傳 POCO List + JSON (Web API) 或啟用壓縮。 |
| 跨平台相容性 | ASMX 遵循 WS-I Basic Profile,Java/Python 等可用 SOAP 客戶端呼叫。 |
| 現代化替代 | 新專案建議採用 ASP.NET Core Web API (REST/JSON) 或 gRPC。 |