How to create a SOAP API request with Username Token in .Net

This c#.net tutorial explains, how to create a SOAP API request with user name token in .Net while connecting to a web service.

Create a SOAP API request with Username Token in .Net

Suppose I have a Web service URL from which I want to retrieve the data from outside organizations.

https://15.32.54.09:80/enjoySharePoint_HTTPRouter/enjoySharePointWebservice

Here I am using SOAP UI to call the secure web service using WCF. The SOAP header I need to generate to do this should contain a username, password, and created mob…

Here is an example of a soap UI header that I use to hit the same service.

create a soap header request
create a soap header request

How to get the same information using C # code

Step 1: Open the Visual Studio – > Create a new console application

create a SOAP API request with Username Token
create a SOAP API request with Username Token

Step 2: Go to the references and add a service reference as per the below screenshot.

create a soap header request
create a soap header request

Step 3: Add the above web service in your service reference and click on Go – > Change the namespace name to any custom name -> Click on OK after getting “GetUserInfo” function over here.

how to create a SOAP API request with Username Token
how to create a SOAP API request with Username Token

Step 4: Next, copy and paste the below code which we can used to get the service output

 [WebMethod]
        public string GetUserInfo()
        {
            Soap.UserDTO dto = new Soap.UserDTO();

            try
            {
                Soap.UserBeanSEIClient client = new Soap.UserBeanSEIClient();
                client.ClientCredentials.UserName.UserName = "rswain";
                client.ClientCredentials.UserName.Password = "password@123";
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) => true);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                PasswordDigestBehavior behavior = new PasswordDigestBehavior("rswain", "password@123");
                client.Endpoint.Behaviors.Add(behavior);
                dto = client.getUserInfo("8873493980", "37232732", "kswain");
                var tem = dto;              
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return dto.cpyEngName;
        }

Note: Sometimes we will get certificate issues while connecting to outside service. So here we will call a method called PasswordDigestBehavior to generate the certificate automatically.

create a soap header request c#.net
create a soap header request c#.net

Step 6: Next create one more class called PasswordDigestBehavior and copy and paste the below code.

PasswordDigestBehavior.cs

using Microsoft.Web.Services3.Security.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Web;
using System.Xml;

namespace COTCWS
{
    partial class PasswordDigestBehavior : IEndpointBehavior
    {


        public string Username { get; set; }
        public string Password { get; set; }


        public PasswordDigestBehavior(string username, string password)
        {
            this.Username = username;
            this.Password = password;
        }


        void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            return;// throw new NotImplementedException();
        }


        void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new PasswordDigestMessageInspector(this.Username, this.Password));

        }

        void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            return;// throw new NotImplementedException();
        }

        void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
        {
            return;// throw new NotImplementedException();
        }
    }


    partial class PasswordDigestMessageInspector : IClientMessageInspector
    {
        public string Username { get; set; }
        public string Password { get; set; }


        public PasswordDigestMessageInspector(string username, string password)
        {
            this.Username = username;
            this.Password = password;
        }


        void IClientMessageInspector.AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            return;// throw new NotImplementedException();
        }


        object IClientMessageInspector.BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            // Use the WSE 3.0 security token class
            UsernameToken token = new UsernameToken(this.Username, this.Password, PasswordOption.SendPlainText);

            // Serialize the token to XML
            XmlElement securityToken = token.GetXml(new XmlDocument());

            //
            MessageHeader securityHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", securityToken, false);
            request.Headers.Add(securityHeader);

            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();
            try
            {
                System.IO.File.WriteAllText(@"c:\temp\testthord\" + DateTime.Now.ToString("MMddyyyyhhmmssfff") + ".xml", request.ToString());
            }
            catch { }

            // complete
            return Convert.DBNull;

            //throw new NotImplementedException();
        }
    }
}

Step 7: Next build the code and debug. Now you can get the output that is the same as your SOAP UI output.

You may like the following tutorials:

This is the process to retrieve results from SOAP API.