萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 建立 Web Service (ASMX) 完整入門教學與資料庫存取範例

前言

ASP.NET Web Service (.asmx) 雖屬舊世代技術,但在維護舊系統或需快速對外暴露 SOAP 介面時仍具實用價值。本文帶領從專案建立、方法撰寫、資料庫存取到用戶端呼叫的完整流程。

一、建立 Web Service 專案

  1. Visual Studio → 新增專案 → ASP.NET Web Service Application (或在既有網站右鍵「加入」→「Web Service」)。
  2. 預設產生 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

[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 回傳
    }
}

改進說明:

  • 使用參數化查詢避免 SQL 注入。
  • using 區塊確保連線正確釋放。
  • 回傳 DataSet 而非 DataTable,前者包含結構描述,用戶端反序列化更容易。

四、測試與發布

  1. 按 F5 執行,瀏覽器開啟 Service1.asmx 測試頁,點擊方法名稱可輸入參數並送出測試。
  2. 發布至 IIS:建立應用程式集區 (.NET 4.0 整合模式),將專案發布至實體路徑,設定虛擬目錄轉換為應用程式。

五、用戶端呼叫方式

1. Visual Studio 「加入 Web 參考」/「加入服務參考」

輸入 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"]}");

2. 直接 HTTP POST (無 Proxy)

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。
copyright © 萬盛學電腦網 all rights reserved