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.
How to get the same information using C # code
Step 1: Open the Visual Studio – > Create a new console application
Step 2: Go to the references and add a service reference as per the below screenshot.
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.
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 = "[email protected]";
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) => true);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
PasswordDigestBehavior behavior = new PasswordDigestBehavior("rswain", "[email protected]");
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.
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:
- How to Implement Log4Net in ASP.NET Core Application
- Why is .NET so popular for web application development
- How to create a folder if not exist in C#.Net
- The following feature couldn’t be installed .net framework 3.5
- Generate One Time Password (OTP) in Asp.Net using C#.Net
- How to create a SOAP API request with Username Token in .Net
- SharePoint and .Net Interview questions and answers
- How to create a GUID in C#.Net
This is the process to retrieve results from SOAP API.
Rajkiran is currently working as a SharePoint Consultant in India . Rajkiran having 7+ years of experience in Microsoft Technologies such as SharePoint 2019/2016/2013/2010, MOSS 2007,WSS 3.0, Migration, Asp.Net, C#.Net, Sql Server, Ajax, jQuery etc.He is C#Corner MVP (2 Times).
Dear Raajkiran Swami, You have a nice post I see there are the ultimate solutions you have 👍
I have a question regarding SOAP with the Attachment. How it is possible in C#