Consume SOAP service with HttpClient in .NET doesn’t have to be hard.
In recent days I need to consume some soap services in .NET 6, and I need to review some concepts about SOAP services in C#.
After doing some research I found some examples using HttpWebRequest, but this class is marked as obsolete in .NET 6 and is suggested to use HttpClient instead, as is showed in the following image.
Next I will show you the code using HttpWebRequest.
public class SoapWebRequest { public string WsdlEnpdoint { get; set; } public HttpWebRequest CreateSOAPWebRequest() { //Making Web Request HttpWebRequest Req = (HttpWebRequest)HttpWebRequest.Create(WsdlEnpdoint); Req.ContentType = "text/xml;charset=\"utf-8\""; Req.Accept = "text/xml"; //HTTP method Req.Method = "POST"; //return HttpWebRequest return Req; } public ReceptionResponse InvokeService(string base64XML) { //Calling CreateSOAPWebRequest method HttpWebRequest request = CreateSOAPWebRequest(); XmlDocument SOAPReqBody = new XmlDocument(); //SOAP Body Request SOAPReqBody.LoadXml(GetSoapXml(base64XML)); using (Stream stream = request.GetRequestStream()) { SOAPReqBody.Save(stream); } //Geting response from request using (WebResponse Serviceres = request.GetResponse()) { using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream())) { //reading stream var ServiceResult = rd.ReadToEnd(); //... process response result (deserialization, save on db) } } return result; } }
The same result and more cleaner could be obtained with HttpClient as is showed in the next code :
string url = ""; HttpClient client = new HttpClient(); HttpRequestMessage httpRequestMessage = new HttpRequestMessage { RequestUri = new Uri(url), Method = HttpMethod.Post, }; httpRequestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/xml")); string strContent = GetSoapXml(); StringContent content = new StringContent(strContent, Encoding.UTF8, "text/xml"); httpRequestMessage.Content = content; var response = client.SendAsync(httpRequestMessage).Result; string contentResponse = response.Content.ReadAsStringAsync().Result; //... process request result (Deserialization, Save on DB)
In the previous example I am using POST method, but it could be change to any http method.
I hope this post could help you.
Check my previous post: How To Make an API with Azure Functions and OpenAPI Support