萬盛學電腦網

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

C# 調用 PHP SOAP Web Service 實戰:NuSOAP 搭建與跨語言通信

架構概覽

PHP 端:NuSOAP 庫實現 SOAP Server,發布 WSDL,註冊方法。
C# 端:Visual Studio「添加服務引用」自動生成代理類,強類型調用。

PHP 服務端實現 (NuSOAP)

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

// 1. 創建 SOAP Server
$server = new soap_server();

// 2. 配置 WSDL 元數據
$namespace = 'https://api.example.com/soap';
$server->configureWSDL('UserService', $namespace);
$server->wsdl->schemaTargetNamespace = $namespace;

// 3. 註冊複雜類型 (可選,用於結構化參數/返回)
$server->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[]'], // 陣列
    ]
);

// 4. 註冊服務方法
$server->register(
    'loginVerify',                    // 方法名
    [                                 // 輸入參數
        'username' => 'xsd:string',
        'password' => 'xsd:string',
    ],
    [                                 // 輸出參數
        'return' => 'tns:UserInfo',   // 返回複雜類型
    ],
    $namespace,                       // 命名空間
    $namespace . '#loginVerify',      // SOAPAction
    'rpc',                            // 風格: rpc | document
    'encoded',                        // 編碼: encoded | literal
    '用戶登錄驗證,返回用戶信息'       // 文檔
);

// 5. 處理請求
$rawPost = file_get_contents('php://input') ?: $GLOBALS['HTTP_RAW_POST_DATA'] ?? '';
$server->service($rawPost);

/** 
 * 業務邏輯實現
 * @param string $username
 * @param string $password
 * @return array 結構對應 UserInfo
 */
function loginVerify(string $username, string $password): array
{
    // 實際應查詢資料庫、驗證密碼雜湊
    if ($username === 'admin' && $password === 'secret123') {
        return [
            'id'       => 1,
            'username' => 'admin',
            'email'    => 'admin@example.com',
            'roles'    => ['admin', 'user'],
        ];
    }
    // 拋出 SOAP Fault
    throw new SoapFault('Client', '用戶名或密碼錯誤', null, 'INVALID_CREDENTIALS');
}
?>

WSDL 自動生成驗證

訪問 https://your-server/server.php?wsdl 應返回 XML 格式的 WSDL 文檔,包含類型定義、消息、端口、綁定等。

C# 客戶端調用

方式一:Visual Studio 添加服務引用 (推薦,強類型)

  1. 右鍵專案 → Add Service Reference
  2. Address 填入:https://your-server/server.php?wsdl
  3. Namespace 填入:PhpSoapService
  4. 生成代理類:PhpSoapService.UserServiceClient
// Program.cs
using System;
using PhpSoapService; // 服務引用命名空間

class Program
{
    static void Main()
    {
        // 從配置讀取端點 (app.config 中自動生成)
        using var client = new UserServiceClient();
        
        try 
        {
            var result = client.loginVerify("admin", "secret123");
            Console.WriteLine($"登錄成功: ID={result.id}, User={result.username}, Email={result.email}");
            Console.WriteLine("Roles: " + string.Join(", ", result.roles));
        }
        catch (System.ServiceModel.FaultException ex)
        {
            Console.WriteLine($"SOAP Fault: {ex.Code.Name} - {ex.Reason}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"通信異常: {ex.Message}");
        }
    }
}

方式二:ChannelFactory 動態調用 (無需預生成代理)

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

[ServiceContract(Namespace = "https://api.example.com/soap")]
public interface IUserService
{
    [OperationContract(Action = "https://api.example.com/soap#loginVerify")]
    UserInfo loginVerify(string username, string password);
}

[DataContract(Namespace = "https://api.example.com/soap")]
public class UserInfo
{
    [DataMember] public int id { get; set; }
    [DataMember] public string username { get; set; }
    [DataMember] public string email { get; set; }
    [DataMember] public string[] roles { get; set; }
}

class Program
{
    static void Main()
    {
        var binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
        var endpoint = new EndpointAddress("https://your-server/server.php");
        
        var factory = new ChannelFactory(binding, endpoint);
        var client = factory.CreateChannel();
        
        try 
        {
            var info = client.loginVerify("admin", "secret123");
            Console.WriteLine($"Welcome {info.username} ({string.Join(",", info.roles)})");
        }
        catch (FaultException fe)
        {
            Console.WriteLine($"Error: {fe.Reason}");
        }
        finally
        {
            ((IClientChannel)client).Close();
            factory.Close();
        }
    }
}

配置文件 (app.config) 關鍵點

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="UserServiceBinding" 
                 maxBufferSize="2147483647" 
                 maxReceivedMessageSize="2147483647"
                 receiveTimeout="00:10:00"
                 sendTimeout="00:10:00">
          <security mode="None" /> <!-- HTTPS 時改 Transport -->
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://your-server/server.php"
                binding="basicHttpBinding"
                bindingConfiguration="UserServiceBinding"
                contract="PhpSoapService.UserService"
                name="UserServicePort" />
    </client>
  </system.serviceModel>
</configuration>

常見坑點與解決

問題原因解決
C# 報「無法導入 WSDL」NuSOAP 生成的 WSDL 不完全符合 WS-I Basic Profile用 wsdl.exe 或 svcutil.exe 命令行生成代理,或手動修正 WSDL
複雜類型陣列序列化失敗NuSOAP xsd:string[] 映射問題改用 soapenc:Array 或簡化為 JSON 字符串傳遞
中文亂碼編碼不一致PHP 端 header('Content-Type: text/xml; charset=utf-8'),C# 端 Binding 設置 TextEncoding = Encoding.UTF8
大數據傳輸超時/超限默認配額 64KB調大 maxReceivedMessageSize, readerQuotas
HTTPS 證書驗證失敗自簽證書/CA 不信任開發期 ServicePointManager.ServerCertificateValidationCallback += (s,e,c,p) => true;

現代替代方案:REST + JSON

SOAP 複雜、XML 冗長、調試困難。新項目**強烈建議 REST API + JSON**:

// PHP: Slim/Laravel/ApiPlatform 暴露 REST
$app->post('/api/login', function(Request $req) {
    return ['token' => 'jwt...', 'user' => [...]];
});

// C#: HttpClient + System.Text.Json
var client = new HttpClient();
var resp = await client.PostAsJsonAsync("https://api/login", new {username, password});
var data = await resp.Content.ReadFromJsonAsync();

總結

NuSOAP 讓 PHP 快速暴露 SOAP 服務,C# 通過服務引用實現強類型調用,適合**企業級異構系統集成**、**銀行/政企規範要求 SOAP** 的場景。但需注意 WSDL 兼容性、編碼、大數據傳輸配置。現代架構首選 REST/JSON/gRPC,開發效率與性能雙優。

copyright © 萬盛學電腦網 all rights reserved