首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

C# 呼叫 PHP SOAP Web Service 完整實作:NuSOAP 伺服端與 C# 客戶端

     編輯:PHP 綜合知識

架構概覽

  • 伺服端: PHP + NuSOAP 庫實作 SOAP 1.1 服務
  • 客戶端: C# (WinForms) 透過 Web Reference 呼叫
  • 通訊協定: HTTP + XML (SOAP)
  • 資料格式: RPC 風格、Encoded 编碼

PHP 伺服端實作

<?php
// server.php
require_once 'lib/nusoap.php'; // NuSOAP 庫

$server = new soap_server();
$server->configureWSDL('login_service', 'https://www.example.com');
$server->wsdl->schemaTargetNamespace = 'https://www.example.com';

// 註冊方法:login_verifiy(string $name, string $pw) : string
$server->register(
    'login_verifiy',                    // 方法名
    ['name' => 'xsd:string', 'pw' => 'xsd:string'], // 輸入參數
    ['return' => 'xsd:string'],         // 輸出參數
    'https://www.example.com',           // namespace
    false,                              // soapaction
    'rpc',                              // style: rpc/document
    'encoded',                          // use: encoded/literal
    '驗證使用者登入帳密'                 // documentation
);

// 處理請求
$post_data = $GLOBALS['HTTP_RAW_POST_DATA'] ?? '';
$server->service($post_data);

/** 實作邏輯 */
function login_verifiy(string $name, string $pw): string {
    // 實際專案應查詢資料庫、驗證密碼雜湊
    if ($name === 'admin' && $pw === '123456') {
        return "登入成功:歡迎 $name";
    }
    return "登入失敗:帳號或密碼錯誤";
}

WSDL 自動生成

瀏覽器開啟 https://yourhost/server.php?wsdl 即可看到自動生成的 WSDL 文件,C# 將以此為依據生成 Proxy 類別。

C# 客戶端實作

1. 新增 Web Reference

Visual Studio 專案右鍵 → Add Service Reference → Advanced → Add Web Reference → 輸入 WSDL 網址 → 命名空間設為 WebReference。

2. 呼叫程式碼

using System;
using System.Windows.Forms;

namespace SoapClientDemo {
    public partial class Form1 : Form {
        private string serviceUrl = "https://localhost/server.php";

        public Form1() {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e) {
            try {
                // 建立 Proxy(Visual Studio 自動生成的類別)
                WebReference.login_service service = new WebReference.login_service();
                service.Url = serviceUrl; // 可動態切換

                // 呼叫遠端方法
                string result = service.login_verifiy(txtUser.Text, txtPass.Text);
                
                MessageBox.Show(result, "伺服器回應");
            } catch (Exception ex) {
                MessageBox.Show($"呼叫失敗:{ex.Message}", "錯誤");
            }
        }
    }
}

3. 設定檔管理端點

app.config 自動生成:

<configuration>
  <applicationSettings>
    <SoapClientDemo.Properties.Settings>
      <setting name="WebReference_login_service" serializeAs="String">
        <value>https://localhost/server.php</value>
      </setting>
    </SoapClientDemo.Properties.Settings>
  </applicationSettings>
</configuration>

進階主題

複雜型別傳遞

wsdl->addComplexType(
    'UserInfo',
    'complexType',
    'struct',
    'all',
    '',
    [
        'id'       => ['name' => 'id', 'type' => 'xsd:int'],
        'username' => ['name' => 'username', 'type' => 'xsd:string'],
        'email'    => ['name' => 'email', 'type' => 'xsd:string'],
        'roles'    => ['name' => 'roles', 'type' => 'xsd:string[]'],
    ]
);

$server->register('get_user', ['uid' => 'xsd:int'], ['return' => 'tns:UserInfo'], ...);

錯誤處理:SOAP Fault

效能與安全建議

  • 生產環境務必使用 HTTPS 加密傳輸
  • NuSOAP 已停止維護,新專案建議改用 PHP 內建 SoapServer 或 現代框架
  • 加入 IP 白名單、API Key、簽名驗證等存取控制
  • 啟用 WSDL 快取:ini_set('soap.wsdl_cache_enabled', 1);

除錯技巧

  • PHP 端:$server->setDebug($debug_flag); 開啟除錯輸出
  • C# 端:使用 Fiddler/Postman 攔截 SOAP 封包
  • 記錄原始 XML 請求/回應至 Log 檔案
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved