Implementing SOAP Request and Response in C#

Nov 01, 2025 · Programming · 8 views · 7.8

Keywords: SOAP | C# | WebService | HttpWebRequest | XML

Abstract: This article provides a comprehensive guide on creating a C# client for SOAP web services, including core code examples, asynchronous handling, error troubleshooting, and best practices. Based on community best answers, it offers step-by-step explanations and in-depth analysis to help developers build reliable SOAP client applications.

Introduction

SOAP (Simple Object Access Protocol) is a protocol used for web services that enables programs to exchange structured information over HTTP. In C#, developers can implement SOAP clients using the HttpWebRequest class to send requests and receive responses. This article builds on best-practice code to deliver a detailed implementation guide, covering the full process from request construction to response handling.

Core Implementation

The core of sending a SOAP request involves creating an HTTP POST request with the SOAP envelope as the XML body. Key steps include setting HTTP headers such as Content-Type and SOAPAction, handling request and response streams, and managing authentication if required. Using the HttpWebRequest class allows for flexible control over these details, ensuring compatibility with SOAP services.

Code Example

The following code is rewritten from the best answer, demonstrating how to send a SOAP request and handle the response. It uses asynchronous methods to avoid thread blocking, making it suitable for scenarios like Windows services.

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Xml;

public static class SoapClient
{
    public static void CallWebService(string url, string action, string soapEnvelopeXml)
    {
        HttpWebRequest webRequest = CreateWebRequest(url, action);
        InsertSoapEnvelope(soapEnvelopeXml, webRequest);
        
        IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
        asyncResult.AsyncWaitHandle.WaitOne();
        
        using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
        {
            using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
            {
                string soapResult = rd.ReadToEnd();
                Console.WriteLine(soapResult);
            }
        }
    }
    
    private static HttpWebRequest CreateWebRequest(string url, string action)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Headers.Add("SOAPAction", action);
        webRequest.ContentType = "text/xml;charset=\"utf-8\"";
        webRequest.Accept = "text/xml";
        webRequest.Method = "POST";
        return webRequest;
    }
    
    private static void InsertSoapEnvelope(string soapEnvelopeXml, HttpWebRequest webRequest)
    {
        using (Stream stream = webRequest.GetRequestStream())
        {
            byte[] bytes = Encoding.UTF8.GetBytes(soapEnvelopeXml);
            stream.Write(bytes, 0, bytes.Length);
        }
    }
}

This code starts by creating a web request, setting necessary headers, writing the SOAP envelope to the request stream, and using BeginGetResponse for asynchronous invocation with WaitOne for completion waiting, finally reading the response. This approach is suitable for scenarios requiring simple asynchronous handling, but note that it may block threads; for UI applications, non-blocking async patterns are recommended.

Asynchronous Processing

In the example, BeginGetResponse and EndGetResponse are used for asynchronous operations, but the thread is blocked with WaitOne to achieve synchronous waiting. For modern C# applications, it is advisable to use the async and await keywords for non-blocking asynchronous code. For instance, methods can be rewritten using GetResponseAsync and stream async methods to improve application responsiveness and scalability, especially in high-concurrency environments like web services or mobile apps.

Error Handling and Troubleshooting

Common errors when sending SOAP requests include incorrect URLs, malformed XML, authentication issues, or network timeouts. Based on reference articles, it is recommended to check the SOAP envelope structure, ensure the SOAPAction header matches the service expectations, and set necessary credentials. For IIS-hosted services, verify authentication methods (e.g., Windows Integrated Authentication), file permissions, and registry settings. If errors like "Sending the SOAP message failed" occur, troubleshoot network connectivity, SSL configurations, and endpoint accessibility.

Best Practices

To ensure the reliability of SOAP clients, use validated code libraries, prioritize asynchronous methods to avoid thread blocking, and handle exceptions properly (e.g., WebException). When parsing SOAP responses, employ XmlDocument or other XML libraries for validation. For new projects, consider higher-level abstractions like WCF or HttpClient, but HttpWebRequest remains effective for fine-grained control. Additionally, regularly test compatibility with various SOAP services and update implementations by referring to official documentation.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.