### Install Simple SOAP Client via NuGet Source: https://github.com/gravity00/simplesoapclient/wiki/Tutorial Use the NuGet Package Manager console to install the library. ```Powershell Install-Package SimpleSOAPClient -Pre ``` -------------------------------- ### Install SimpleSOAPClient via NuGet Source: https://github.com/gravity00/simplesoapclient/blob/Release-v2.x/README.md Use this command to install the SimpleSOAPClient package using the NuGet Package Manager. ```powershell Install-Package SimpleSOAPClient ``` -------------------------------- ### Complete SOAP Request/Response Cycle Example Source: https://context7.com/gravity00/simplesoapclient/llms.txt Demonstrates client creation, handler configuration, request sending, and response processing with comprehensive error handling. Includes custom request serialization, security headers, and response deserialization. ```csharp using SimpleSOAPClient; using SimpleSOAPClient.Exceptions; using SimpleSOAPClient.Handlers; using SimpleSOAPClient.Helpers; using SimpleSOAPClient.Models; using SimpleSOAPClient.Models.Headers; using System; using System.Threading; using System.Threading.Tasks; using System.Xml.Serialization; [XmlRoot("IsAliveRequest", Namespace = "http://services.company.com")] public class IsAliveRequest { } [XmlRoot("IsAliveResponse", Namespace = "http://services.company.com")] public class IsAliveResponse { [XmlElement("IsAliveResult")] public bool IsAlive { get; set; } [XmlElement("ServerTime")] public DateTime ServerTime { get; set; } } public class SoapService { private readonly string _serviceUrl; private readonly string _username; private readonly string _password; public SoapService(string serviceUrl, string username, string password) { _serviceUrl = serviceUrl; _username = username; _password = password; } public async Task CheckServiceHealthAsync(CancellationToken ct) { using (var client = SoapClient.Prepare() .UsingClientConfiguration(http => http.Timeout = TimeSpan.FromSeconds(10)) .WithHandler(new DelegatingSoapHandler { Order = int.MaxValue, OnSoapEnvelopeRequestAsyncAction = async (c, args, cancellationToken) => { args.Envelope.WithHeaders( KnownHeader.Oasis.Security.UsernameTokenAndPasswordText( _username, _password)); }, OnHttpRequestAsyncAction = async (c, args, cancellationToken) => { Console.WriteLine($"[{args.TrackingId}] Sending request to {args.Url}"); }, OnHttpResponseAsyncAction = async (c, args, cancellationToken) => { Console.WriteLine($"[{args.TrackingId}] Received {args.Response.StatusCode}"); } })) { var requestEnvelope = SoapEnvelope.Prepare() .Body(new IsAliveRequest()); SoapEnvelope responseEnvelope; try { responseEnvelope = await client.SendAsync( _serviceUrl, "http://services.company.com/IService/IsAlive", requestEnvelope, ct); } catch (SoapEnvelopeSerializationException e) { throw new InvalidOperationException( $"Failed to serialize request: {e.Message}", e); } catch (SoapEnvelopeDeserializationException e) { throw new InvalidOperationException( $"Failed to deserialize response: {e.XmlValue}", e); } try { return responseEnvelope.Body(); } catch (FaultException e) { throw new InvalidOperationException( $"Service returned fault: {e.Code} - {e.String}", e); } } } } // Usage var service = new SoapService( "https://services.company.com/Service.svc", "serviceUser", "servicePassword"); var result = await service.CheckServiceHealthAsync(CancellationToken.None); Console.WriteLine($"Service alive: {result.IsAlive}, Server time: {result.ServerTime}"); ``` -------------------------------- ### Initialize SOAP Client with SoapClient.Prepare Source: https://context7.com/gravity00/simplesoapclient/llms.txt Demonstrates creating a SoapClient instance using default settings, a custom HttpClient, or a custom HttpMessageHandler. Always wrap the client in a using block to ensure proper disposal. ```csharp using SimpleSOAPClient; using SimpleSOAPClient.Helpers; using System; using System.Threading; using System.Threading.Tasks; // Basic client creation using (var client = SoapClient.Prepare()) { // Client is ready to send requests } // Create client with custom HttpClient using (var httpClient = new HttpClient()) using (var client = SoapClient.Prepare(httpClient, disposeHttpClient: false)) { // Uses provided HttpClient } // Create client with custom HttpMessageHandler using (var handler = new HttpClientHandler { UseProxy = true }) using (var client = SoapClient.Prepare(handler)) { // Uses custom handler for HTTP operations } ``` -------------------------------- ### SoapClient.Prepare - Create and Configure SOAP Client Source: https://context7.com/gravity00/simplesoapclient/llms.txt Demonstrates how to create and configure a SoapClient instance using various constructors, including default, custom HttpClient, and custom HttpMessageHandler. ```APIDOC ## SoapClient.Prepare - Create and Configure SOAP Client ### Description The `SoapClient.Prepare()` static method creates a new SOAP client instance ready for configuration. The client implements `IDisposable` and should be used within a `using` block to ensure proper resource cleanup. The fluent API allows chaining configuration methods before sending requests. ### Method `static SoapClient Prepare()` ### Endpoint N/A (Library method) ### Parameters None directly for `Prepare()`, but can accept `HttpClient` or `HttpMessageHandler`. #### Request Body None ### Request Example ```csharp using SimpleSOAPClient; using System.Net.Http; // Basic client creation using (var client = SoapClient.Prepare()) { // Client is ready to send requests } // Create client with custom HttpClient using (var httpClient = new HttpClient()) using (var client = SoapClient.Prepare(httpClient, disposeHttpClient: false)) { // Uses provided HttpClient } // Create client with custom HttpMessageHandler using (var handler = new System.Net.Http.HttpClientHandler { UseProxy = true }) using (var client = SoapClient.Prepare(handler)) { // Uses custom handler for HTTP operations } ``` ### Response An instance of `SoapClient`. ``` -------------------------------- ### Basic SOAP Client Usage with Handlers Source: https://github.com/gravity00/simplesoapclient/blob/Release-v2.x/README.md Demonstrates how to prepare and use the SoapClient with custom handlers for request and response processing. Includes error handling for serialization and deserialization exceptions, as well as SOAP faults. ```csharp public static async Task MainAsync(string[] args, CancellationToken ct) { using (var client = SoapClient.Prepare() .WithHandler(new DelegatingSoapHandler { OnSoapEnvelopeRequestAsyncAction = async (c, d, cancellationToken) => { d.Envelope.WithHeaders( KnownHeader.Oasis.Security.UsernameTokenAndPasswordText( "some-user", "some-password")); }, OnHttpRequestAsyncAction = async (soapClient, d, cancellationToken) => { Logger.LogTrace( "SOAP Outbound Request -> {0} {1}({2})\n{3}", d.Request.Method, d.Url, d.Action, await d.Request.Content.ReadAsStringAsync()); }, OnHttpResponseAsyncAction = async (soapClient, d, cancellationToken) => { Logger.LogTrace( "SOAP Outbound Response -> {0}({1}) {2} {3}\n{4}", d.Url, d.Action, (int) d.Response.StatusCode, d.Response.StatusCode, await d.Response.Content.ReadAsStringAsync()); }, OnSoapEnvelopeResponseAsyncAction = async (soapClient, d, cancellationToken) => { var header = d.Envelope.Header( "{" + Constant.Namespace.OrgOpenOasisDocsWss200401Oasis200401WssWssecuritySecext10 + "}Security"); } })) { var requestEnvelope = SoapEnvelope.Prepare().Body(new IsAliveRequest()); SoapEnvelope responseEnvelope; try { responseEnvelope = await client.SendAsync( "https://services.company.com/Service.svc", "http://services.company.com/IService/IsAlive", requestEnvelope, ct); } catch (SoapEnvelopeSerializationException e) { Logger.LogError(e, $"Failed to serialize the SOAP Envelope [Envelope={e.Envelope}]"); throw; } catch (SoapEnvelopeDeserializationException e) { Logger.LogError(e, $"Failed to deserialize the response into a SOAP Envelope [XmlValue={e.XmlValue}]"); throw; } try { var response = responseEnvelope.Body(); } catch (FaultException e) { Logger.LogError(e, $"The server returned a fault [Code={e.Code}, String={e.String}, Actor={e.Actor}]"); throw; } } } ``` -------------------------------- ### SoapEnvelope.Prepare - Create SOAP Envelopes Source: https://context7.com/gravity00/simplesoapclient/llms.txt Illustrates how to create SOAP envelopes using `SoapEnvelope.Prepare()` and populate them with a body. It also shows the requirement for `XmlRoot` and `XmlElement` attributes on request and response types. ```APIDOC ## SoapEnvelope.Prepare - Create SOAP Envelopes ### Description The `SoapEnvelope.Prepare()` method creates a new SOAP envelope that can be populated with headers and a body. SOAP body and header types must use `XmlRoot` and `XmlElement` attributes for proper XML serialization. ### Method `static SoapEnvelope Prepare()` ### Endpoint N/A (Library method) ### Parameters None #### Request Body None ### Request Example ```csharp using SimpleSOAPClient.Models; using System.Xml.Serialization; // Define request and response types [XmlRoot("CreateUserRequest", Namespace = "http://services.company.com")] public class CreateUserRequest { [XmlElement("Username")] public string Username { get; set; } [XmlElement("Password")] public string Password { get; set; } } // Create envelope with body var requestEnvelope = SoapEnvelope.Prepare() .Body(new CreateUserRequest { Username = "john.doe@company.com", Password = "SecurePassword123" }); ``` ### Response An instance of `SoapEnvelope`. ``` -------------------------------- ### Define Models and Create SOAP Envelopes Source: https://context7.com/gravity00/simplesoapclient/llms.txt Shows how to define request/response classes with XML attributes and populate a SOAP envelope body. ```csharp using SimpleSOAPClient.Models; using System.Xml.Serialization; // Define request and response types [XmlRoot("CreateUserRequest", Namespace = "http://services.company.com")] public class CreateUserRequest { [XmlElement("Username")] public string Username { get; set; } [XmlElement("Password")] public string Password { get; set; } } [XmlRoot("CreateUserResponse", Namespace = "http://services.company.com")] public class CreateUserResponse { [XmlElement("Succeeded")] public bool Succeeded { get; set; } [XmlElement("UserId")] public int UserId { get; set; } } // Create envelope with body var requestEnvelope = SoapEnvelope.Prepare() .Body(new CreateUserRequest { Username = "john.doe@company.com", Password = "SecurePassword123" }); ``` -------------------------------- ### Initialize SoapClient Source: https://github.com/gravity00/simplesoapclient/wiki/Tutorial SoapClient implements IDisposable and should be managed within a using block. ```csharp using(var client = new SoapClient()){ } using(var client = SoapClient.Prepare()){ } ``` -------------------------------- ### Configuring Client Settings Source: https://context7.com/gravity00/simplesoapclient/llms.txt Customize the underlying HttpClient via UsingClientConfiguration or apply custom serialization and factory settings using UsingSettings. ```csharp using SimpleSOAPClient; using SimpleSOAPClient.Helpers; using System; using System.Net.Http; // Configure HttpClient timeout and default headers using (var client = SoapClient.Prepare() .UsingClientConfiguration(httpClient => { httpClient.Timeout = TimeSpan.FromSeconds(30); httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0"); httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US"); })) { var response = await client.SendAsync(url, action, envelope, ct); } // Use custom settings var customSettings = new SoapClientSettings { SerializationProvider = new CustomSerializationProvider(), HttpClientFactory = new CustomHttpClientFactory() }; using (var client = SoapClient.Prepare() .UsingSettings(customSettings)) { var response = await client.SendAsync(url, action, envelope, ct); } // Reset to default settings using (var client = SoapClient.Prepare() .UsingDefaultSettings()) { var response = await client.SendAsync(url, action, envelope, ct); } ``` -------------------------------- ### Implement Advanced SOAP Client with Handlers Source: https://github.com/gravity00/simplesoapclient/wiki/Tutorial Configures a SOAP client with custom headers and logging handlers, and demonstrates sending a request with error handling. ```csharp public static class Program { // NLog in this case private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); public static void Main(string[] args) { try { Logger.Info("Application started..."); MainAsync(args, CancelationToken.None).Wait(CancelationToken.None); } catch (Exception e) { Logger.Fatal(e, "An unexpected exception has occured"); } finally { Logger.Info("Application terminated. Press to exit..."); Console.ReadLine(); } } public static async Task MainAsync(string[] args, CancelationToken ct) { using(var client = SoapClient.Prepare() .WithHandler(new DelegatingSoapHandler { Order = int.MaxValue, // Will be the last handler before the request and the first after the response OnSoapEnvelopeRequest = args => { args.Envelope.WithHeaders(new TrackingHeader { Id = args.TrackingId, CreatedOn = DateTime.UtcNow }, KnownHeader.Oasis.Security.UsernameTokenAndPasswordText("some-user", "some-password")); } OnHttpRequestAsyncAction = async (c, args, cnt) => { Logger.Trace( "SOAP Outbound Request [{0}] -> {1} {2}({3})\n{4}", args.TrackingId, args.Request.Method, args.Url, args.Action, await args.Request.Content.ReadAsStringAsync()); }, OnHttpResponseAsyncAction = async (c, args, cnt) => { Logger.Trace( "SOAP Outbound Response [{0}] -> {1}({2}) {3} {4}\n{5}", args.TrackingId, args.Url, args.Action, (int) args.Response.StatusCode, args.Response.StatusCode, await args.Response.Content.ReadAsStringAsync()); } })){ var requestEnvelope = SoapEnvelope.Prepare().Body(new CreateUserRequest { Username = "someemail@company.com", Password = "amazing, my password is!!!" }); SoapEnvelope responseEnvelope; try { responseEnvelope = await client.SendAsync( "https://services.company.com/Service.svc", "http://services.company.com/IService/CreateUser", requestEnvelope, ct); } catch (SoapEnvelopeSerializationException e) { Logger.Error(e, $"Failed to serialize the SOAP Envelope [Envelope={e.Envelope}]"); throw; } catch (SoapEnvelopeDeserializationException e) { Logger.Error(e, $"Failed to deserialize the response into a SOAP Envelope [XmlValue={e.XmlValue}]"); throw; } try { var response = responseEnvelope.Body(); Logger.Debug("Response-> Suceeded: {0}", response.Suceeded); } catch (FaultException e) { Logger.Error(e, $"The server returned a fault [Code={e.Code}, String={e.String}, Actor={e.Actor}]"); throw; } } } } [XmlRoot("CreateUserRequest", Namespace = "http://services.company.com")] public class CreateUserRequest { [XmlElement("Username")] public string Username { get; set; } [XmlElement("Password")] public string Password { get; set; } } [XmlRoot("CreateUserResponse", Namespace = "http://services.company.com")] public class CreateUserResponse { [XmlElement("Suceeded")] public bool Suceeded { get; set; } } [XmlRoot("Tracking", Namespace = "http://services.company.com")] public class TrackingHeader : SimpleSOAPClient.Models.SoapHeader { [XmlElement("Id")] public Guid Id { get; set; } [XmlElement("CreatedOn")] public DateTime CreatedOn { get; set; } public TrackingHeader() { MustUnderstand = 0; // this is the default value } } ``` -------------------------------- ### Configure Security and Addressing Headers with KnownHeader Source: https://context7.com/gravity00/simplesoapclient/llms.txt Utilizes factory methods for standard WS-Security and Microsoft WS-Addressing headers. ```csharp using SimpleSOAPClient.Helpers; using SimpleSOAPClient.Models; using SimpleSOAPClient.Models.Headers; // Add WS-Security UsernameToken authentication var envelope = SoapEnvelope.Prepare() .WithHeaders( KnownHeader.Oasis.Security.UsernameTokenAndPasswordText( username: "serviceAccount", password: "servicePassword", mustUnderstand: true)) .Body(new SecureOperationRequest()); // Add Microsoft WS-Addressing headers var envelopeWithAddressing = SoapEnvelope.Prepare() .WithHeaders( KnownHeader.Microsoft.Action( "http://services.company.com/IService/DoSomething", mustUnderstand: true), KnownHeader.Microsoft.To( "https://services.company.com/Service.svc", mustUnderstand: true)) .Body(new DoSomethingRequest()); ``` -------------------------------- ### Implement Request/Response Handlers with WithHandler Source: https://context7.com/gravity00/simplesoapclient/llms.txt Intercepts SOAP pipeline stages using DelegatingSoapHandler. Execution order is determined by the Order property. ```csharp using SimpleSOAPClient; using SimpleSOAPClient.Handlers; using SimpleSOAPClient.Helpers; using SimpleSOAPClient.Models.Headers; using System; using System.Threading; using System.Threading.Tasks; using (var client = SoapClient.Prepare() .WithHandler(new DelegatingSoapHandler { Order = 0, // Lower values execute first on request, last on response // Modify envelope before serialization OnSoapEnvelopeRequestAsyncAction = async (c, args, ct) => { args.Envelope.WithHeaders( KnownHeader.Oasis.Security.UsernameTokenAndPasswordText( "user", "password")); }, // Log outgoing HTTP request OnHttpRequestAsyncAction = async (c, args, ct) => { var content = await args.Request.Content.ReadAsStringAsync(); Console.WriteLine($ ``` -------------------------------- ### Send SOAP Requests with SendAsync Source: https://context7.com/gravity00/simplesoapclient/llms.txt Illustrates sending a SOAP envelope to a service endpoint and handling potential serialization, deserialization, or server fault exceptions. ```csharp using SimpleSOAPClient; using SimpleSOAPClient.Exceptions; using SimpleSOAPClient.Helpers; using SimpleSOAPClient.Models; using System; using System.Threading; using System.Threading.Tasks; public async Task CreateUserAsync( string username, string password, CancellationToken ct) { using (var client = SoapClient.Prepare()) { var requestEnvelope = SoapEnvelope.Prepare() .Body(new CreateUserRequest { Username = username, Password = password }); SoapEnvelope responseEnvelope; try { responseEnvelope = await client.SendAsync( "https://services.company.com/UserService.svc", "http://services.company.com/IUserService/CreateUser", requestEnvelope, ct); } catch (SoapEnvelopeSerializationException e) { Console.WriteLine($"Failed to serialize request: {e.Envelope}"); throw; } catch (SoapEnvelopeDeserializationException e) { Console.WriteLine($"Failed to deserialize response: {e.XmlValue}"); throw; } try { return responseEnvelope.Body(); } catch (FaultException e) { Console.WriteLine($"Server fault - Code: {e.Code}, Message: {e.String}, Actor: {e.Actor}"); throw; } } } ``` -------------------------------- ### Configure SOAP Client with DelegatingSoapHandler Source: https://github.com/gravity00/simplesoapclient/wiki/Tutorial Uses DelegatingSoapHandler to inject security headers and log HTTP traffic. Handlers are executed based on the Order property in ascending order. ```csharp using(var client = SoapClient.Prepare() .WithHandler(new DelegatingSoapHandler { Order = int.MaxValue, // Will be the last handler before the request and the first after the response OnSoapEnvelopeRequest = args => { args.Envelope.WithHeaders(new TrackingHeader { Id = args.TrackingId, CreatedOn = DateTime.UtcNow }, KnownHeader.Oasis.Security.UsernameTokenAndPasswordText("some-user", "some-password")); } OnHttpRequestAsyncAction = async (c, args, cnt) => { Logger.Trace( "SOAP Outbound Request [{0}] -> {1} {2}({3})\n{4}", args.TrackingId, args.Request.Method, args.Url, args.Action, await args.Request.Content.ReadAsStringAsync()); }, OnHttpResponseAsyncAction = async (c, args, cnt) => { Logger.Trace( "SOAP Outbound Response [{0}] -> {1}({2}) {3} {4}\n{5}", args.TrackingId, args.Url, args.Action, (int) args.Response.StatusCode, args.Response.StatusCode, await args.Response.Content.ReadAsStringAsync()); } })){ var responseEnvelope = await client.SendAsync( "https://services.company.com/Service.svc", "http://services.company.com/IService/CreateUser", SoapEnvelope.Prepare().Body(new CreateUserRequest()), ct); var response = responseEnvelope.Body(); } ``` -------------------------------- ### Define SOAP Envelope Header Classes Source: https://github.com/gravity00/simplesoapclient/wiki/Tutorial Header classes should extend SoapHeader and include the XmlRoot attribute. ```csharp [XmlRoot("Tracking", Namespace = "http://services.company.com")] public class TrackingHeader : SimpleSOAPClient.Models.SoapHeader { [XmlElement("Id")] public Guid Id { get; set; } [XmlElement("CreatedOn")] public DateTime CreatedOn { get; set; } public TrackingHeader() { MustUnderstand = 0; // this is the default value } } ``` -------------------------------- ### Registering Fluent Handlers Source: https://context7.com/gravity00/simplesoapclient/llms.txt Use fluent extension methods to attach request and response handlers for SOAP envelopes and HTTP messages without explicit DelegatingSoapHandler instances. ```csharp using SimpleSOAPClient; using SimpleSOAPClient.Helpers; using System; using System.Threading.Tasks; using (var client = SoapClient.Prepare() .OnSoapEnvelopeRequest(async (args, ct) => { // Add authentication header to all requests args.Envelope.WithHeaders( KnownHeader.Oasis.Security.UsernameTokenAndPasswordText("user", "pass")); }, order: 0) .OnHttpRequest(async (args, ct) => { // Add custom HTTP headers args.Request.Headers.Add("X-Correlation-Id", args.TrackingId.ToString()); }, order: 1) .OnHttpResponse(async (args, ct) => { // Validate response status if (!args.Response.IsSuccessStatusCode) { var body = await args.Response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP Error {args.Response.StatusCode}: {body}"); } }, order: 0) .OnSoapEnvelopeResponse(async (args, ct) => { // Post-process response envelope Console.WriteLine($"Request {args.TrackingId} completed"); }, order: 0)) { var response = await client.SendAsync(url, action, envelope, ct); } ``` -------------------------------- ### Define SOAP Envelope Body Classes Source: https://github.com/gravity00/simplesoapclient/wiki/Tutorial Classes representing the SOAP body must be decorated with the XmlRoot attribute. ```csharp [XmlRoot("CreateUserRequest", Namespace = "http://services.company.com")] public class CreateUserRequest { [XmlElement("Username")] public string Username { get; set; } [XmlElement("Password")] public string Password { get; set; } } [XmlRoot("CreateUserResponse", Namespace = "http://services.company.com")] public class CreateUserResponse { [XmlElement("Suceeded")] public bool Suceeded { get; set; } } ``` -------------------------------- ### Add SOAP Headers with WithHeaders Source: https://context7.com/gravity00/simplesoapclient/llms.txt Appends custom SOAP headers to an envelope and retrieves them from a response. Custom headers must extend the SoapHeader class. ```csharp using SimpleSOAPClient.Helpers; using SimpleSOAPClient.Models; using SimpleSOAPClient.Models.Headers; using System; using System.Xml.Serialization; // Custom header type [XmlRoot("Tracking", Namespace = "http://services.company.com")] public class TrackingHeader : SoapHeader { [XmlElement("RequestId")] public Guid RequestId { get; set; } [XmlElement("Timestamp")] public DateTime Timestamp { get; set; } public TrackingHeader() { MustUnderstand = 0; } } // Add custom headers to envelope var envelope = SoapEnvelope.Prepare() .WithHeaders( new TrackingHeader { RequestId = Guid.NewGuid(), Timestamp = DateTime.UtcNow }) .Body(new CreateUserRequest { Username = "test", Password = "pass" }); // Read header from response var responseEnvelope = await client.SendAsync(url, action, envelope, ct); var trackingHeader = responseEnvelope.Header( "{http://services.company.com}Tracking"); ``` -------------------------------- ### SendAsync - Send SOAP Requests Source: https://context7.com/gravity00/simplesoapclient/llms.txt Details the `SendAsync` method for sending SOAP requests to a specified URL with a SOAP action, including handling of serialization, HTTP communication, and response deserialization, along with error handling for common exceptions. ```APIDOC ## SendAsync - Send SOAP Requests ### Description The `SendAsync` method sends a SOAP envelope to a specified URL with a SOAP action and returns the response envelope. It handles serialization of the request, HTTP communication, and deserialization of the response automatically. Error handling for serialization and deserialization exceptions, as well as SOAP faults, is demonstrated. ### Method `Task SendAsync(string url, string soapAction, SoapEnvelope requestEnvelope, CancellationToken ct)` ### Endpoint `[URL]` - The endpoint URL of the SOAP service. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL of the SOAP service endpoint. - **soapAction** (string) - Required - The SOAP action header value. - **requestEnvelope** (SoapEnvelope) - Required - The SOAP envelope to send. - **ct** (CancellationToken) - Required - A token to observe for cancellation. ### Request Example ```csharp using SimpleSOAPClient; using SimpleSOAPClient.Exceptions; using SimpleSOAPClient.Models; using System; using System.Threading; using System.Threading.Tasks; public async Task CreateUserAsync( string username, string password, CancellationToken ct) { using (var client = SoapClient.Prepare()) { var requestEnvelope = SoapEnvelope.Prepare() .Body(new CreateUserRequest { Username = username, Password = password }); SoapEnvelope responseEnvelope; try { responseEnvelope = await client.SendAsync( "https://services.company.com/UserService.svc", "http://services.company.com/IUserService/CreateUser", requestEnvelope, ct); } catch (SoapEnvelopeSerializationException e) { Console.WriteLine($"Failed to serialize request: {e.Envelope}"); throw; } catch (SoapEnvelopeDeserializationException e) { Console.WriteLine($"Failed to deserialize response: {e.XmlValue}"); throw; } try { return responseEnvelope.Body(); } catch (FaultException e) { Console.WriteLine($"Server fault - Code: {e.Code}, Message: {e.String}, Actor: {e.Actor}"); throw; } } } ``` ### Response #### Success Response (200) - **SoapEnvelope** (SoapEnvelope) - The SOAP response envelope. #### Response Example ```json { "responseEnvelope": "..." } ``` #### Error Handling - **SoapEnvelopeSerializationException**: Thrown when the request envelope fails to serialize. - **SoapEnvelopeDeserializationException**: Thrown when the response envelope fails to deserialize. - **FaultException**: Thrown when the SOAP service returns a fault. ``` -------------------------------- ### Manipulate SOAP Envelope Headers Source: https://github.com/gravity00/simplesoapclient/wiki/Tutorial Use EnvelopeHelpers to add or retrieve headers from the SOAP envelope. ```csharp var envelope = SoapEnvelope.Prepare(); envelope.WithHeaders(new TrackingHeader()); var header = envelope.Header("{http://services.company.com}Tracking"); ``` -------------------------------- ### Send SOAP Envelopes Source: https://github.com/gravity00/simplesoapclient/wiki/Tutorial Use SendAsync to transmit the envelope to a specific endpoint and action. ```csharp using(var client = SoapClient.Prepare()){ var responseEnvelope = await client.SendAsync( "https://services.company.com/Service.svc", "http://services.company.com/IService/CreateUser", SoapEnvelope.Prepare() .WithHeaders(new TrackingHeader()) .Body(new CreateUserRequest()), ct); var response = responseEnvelope.Body(); } ``` -------------------------------- ### IsAliveResponse Class Definition Source: https://github.com/gravity00/simplesoapclient/blob/Release-v2.x/README.md Defines the structure for an IsAlive SOAP response. This class is used to represent the body of the SOAP response and includes a boolean property for the IsAlive result. ```csharp [XmlRoot("IsAliveResponse", Namespace = "http://services.company.com")] public class IsAliveResponse { [XmlElement("IsAliveResult")] public bool IsAlive { get; set; } } ``` -------------------------------- ### IsAliveRequest Class Definition Source: https://github.com/gravity00/simplesoapclient/blob/Release-v2.x/README.md Defines the structure for an IsAlive SOAP request. This class is used to represent the body of the SOAP request. ```csharp [XmlRoot("IsAliveRequest", Namespace = "http://services.company.com")] public class IsAliveRequest { } ``` -------------------------------- ### Manipulate SOAP Envelope Body Source: https://github.com/gravity00/simplesoapclient/wiki/Tutorial Use EnvelopeHelpers to assign or retrieve objects from the SOAP body. ```csharp var envelope = SoapEnvelope.Prepare(); envelope.Body(new CreateUserRequest()); var request = envelope.Body(); ``` -------------------------------- ### Handling SOAP Faults Source: https://context7.com/gravity00/simplesoapclient/llms.txt Check for faults manually using IsFaulted or use ThrowIfFaulted to trigger a FaultException. The Body method performs automatic fault checking during deserialization. ```csharp using SimpleSOAPClient.Exceptions; using SimpleSOAPClient.Helpers; using SimpleSOAPClient.Models; var responseEnvelope = await client.SendAsync(url, action, requestEnvelope, ct); // Manual fault checking if (responseEnvelope.IsFaulted()) { var fault = responseEnvelope.Fault(); Console.WriteLine($"Fault Code: {fault.Code}"); Console.WriteLine($"Fault String: {fault.String}"); Console.WriteLine($"Fault Actor: {fault.Actor}"); Console.WriteLine($"Fault Detail: {fault.Detail}"); return; } // Or use ThrowIfFaulted for exception-based handling try { responseEnvelope.ThrowIfFaulted(); var result = responseEnvelope.Body(); } catch (FaultException ex) { Console.WriteLine($"SOAP Fault: {ex.Code} - {ex.String}"); } // Body automatically throws if faulted try { var result = responseEnvelope.Body(); } catch (FaultException ex) { // Handle fault } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.