We will learn how to construct and use Soap Web Services in Dotnet Core in this tutorial. In software development, Web services implementation comes in two flavors: SOAP and REST API. Web Services are programs that enable internet-based device-to-device communication.

Please make sure you have installed

Steps to Create SOAP Demo Application

1. Create a SOAP Webservice in Visual Studio 2019

1. Create an empty ASP.NET Web Application(.NET Framework) .We will use this project as the soap service demo .To do that just follow the steps below.

  • Select File > New > Project.
  • Select ASP.NET Web Application(.NET Framework). Name the project SoapDemo to have the same namespace as my project. Click Create.
  • Select an Empty ASP.NET Web Application(.NET Framework).
  • Lastly, Click on Create.

This is what your solution with an empty template would look like after creating a new project. See the picture below.

2. Add a new item by right-clicking your project solution and select Add » NewItem. Then search for Web Service ASMX.

3. Click the “Add” button to create a template for an ASMX web service that includes the standard web method HelloWorld. View the image that is included below.

We are now prepared to add our sample method, which in my instance will be a login Web Method, as we now have our Soap Web service. This method will check my website’s login credentials and provide an error if they are invalid or don’t exist in my user database.

2. Create a Sample WEB Method Login

To use later in our ASP.Net Core Web Application, let’s construct a sample Login function. To add the sample code, adhere to the steps below.

1. Create a ResponseModel. This will serve as our response model template.

My ResponseModel class has had the following code added. Copy the code snippet below into a new class file with the name ResponseModel.

ResponseModel :

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 namespace SoapDemo.Models
 {
         public class ResponseModel
         {
             public T Data { get; set; }
             public int resultCode { get; set; }
             public string message { get; set; }
         }
 }

2. Next, open the SoapDemo.asmx file and insert the example login validation method that is provided below. With this approach, the User table will be searched for the email and password. This method will return the response code, which is described as follows, once the user has been located in the database.

Response CodeDescription
200Email and password found
500Email and password does not exist

You can choose any response you want to use, but for this example I’m going to use the response code from above. I utilized the database from my earlier tutorial for this example. To construct your own ASP.NET Core login application, click the link below.

You can copy the code snippet below on your SoapDemo.asmx file.

     [WebMethod]
         public  ResponseModel<string> login(string email, string password)
         {
             ResponseModel<string> response = new ResponseModel<string>();
  
             if (email != null)
             {
                 using (SqlConnection conn = new SqlConnection(@"Server=CODERSIGN\SQLEXPRESS01;Database=IdentityDemo;User Id=freecode;Password=freespot;"))
                 {
                     SqlCommand cmd = new SqlCommand("sp_loginUser",conn);
                     cmd.CommandType = CommandType.StoredProcedure;
                     cmd.Parameters.Add("@email", SqlDbType.NVarChar, 50).Value = email;
                     cmd.Parameters.Add("@password", SqlDbType.NVarChar, 50).Value = password;
                     
  
                     SqlDataAdapter da = new SqlDataAdapter(cmd);
                     DataTable dt = new DataTable();
                     da.Fill(dt);
  
  
                     if (dt.Rows.Count > 0)
                     {
                         response.Data = JsonConvert.SerializeObject(dt);
                         response.resultCode = 200;
                     }
                     else
                     {
                         response.message = "User Not Found!";
                         response.resultCode = 500;
                     }
  
  
                 }
             }
             return response;
         } 

3. Now, run your project and make sure you see the method you just created. See the image below.

WebMethodDescription
HelloWorldDefault method created that will return a “Hello World” string
loginlogin validation method

Soap Service URL: https://localhost:44399/SoapDemo.asmx

3. Create a Sample ASP.NET Core Web Application Project.

This is a sample login application that uses cookie authentication

After that open the project using the latest Visual Studio and rebuild the solution.

4. Add a soap service reference for the ASP.NET Core application’s SoapDemo service.

Now, we are ready to consume the soap service that we created above. Run your soap service and follow the steps below.

1. Run your soap service, this will open the browser with the soap service URL. In my case my soap URL is https://localhost:44399/SoapDemo.asmx.

2. Now, navigate to IdentityDemo project solution. Then right click on the Connected Services then Add Connected Service.

3. Select Microsoft WCF Web Service Reference Provider from Other Services option. Then Input your URL and assign the service name.

4. Then click Finish. This will generate references for your Soap Service.

At this point, we have successfully generated the reference for our Web service project.

5. Consume Soap Service on ASP.NET Core Application

Let’s include the Service’s implementation in our project. We will add the interface and implementation to the existing IRepository and Repository classes as the ASP.NET core is an existing project.

This is a summary of how to obtain an instance of the soap service that we recently implemented.

Before you begin the following actions. The following NuGet packages need be installed.

  • System.ServiceModel.Http
  • System.ServiceModel.Premitives

1. From IRepository class we added a GetInstanceAsync method. This method will instatiate the soap service.

Task<SoapDemoClient> GetInstanceAsync();

2. Then on the implementation class which is Repository.cs. I added this code.

public readonly string serviceUrl = "https://localhost:44399/SoapDemo.asmx";
public readonly EndpointAddress endpointAddress;
public readonly BasicHttpBinding basicHttpBinding;

Repository Contructor:

 public Repository(IConfiguration configuration)
         {
             _configuration = configuration;
  
             endpointAddress = new EndpointAddress(serviceUrl);
  
             basicHttpBinding = new BasicHttpBinding(endpointAddress.Uri.Scheme.ToLower() == "http" ?
                             BasicHttpSecurityMode.None : BasicHttpSecurityMode.Transport);
             basicHttpBinding.OpenTimeout = TimeSpan.MaxValue;
             basicHttpBinding.CloseTimeout = TimeSpan.MaxValue;
             basicHttpBinding.ReceiveTimeout = TimeSpan.MaxValue;
             basicHttpBinding.SendTimeout = TimeSpan.MaxValue;
         } 

GetInstanceAsync implementation:

 public async Task<SoapDemoSoapClient> GetInstanceAsync()
    {
         return await Task.Run(() => new SoapDemoSoapClient(basicHttpBinding, endpointAddress));
    } 

3. To use this instance you can call it using the code snippet below.

 var client = await GetInstanceAsync();
 var result = await client.loginAsync(loginView.Email, loginView.Password); 

LoginAsync is the Login method from the SoapDemo service that we added on the Connected Service.

This is now the new code in my LoginAsync method.

  public async Task<Response<IdentityModel>> LoginAsync(LoginViewModel loginView)
         {
             Response<IdentityModel> response = new Response<IdentityModel>();
             IdentityModel userModel = new IdentityModel();
  
             try
             {
                 var client = await GetInstanceAsync();
                 var result = await client.loginAsync(loginView.Email, loginView.Password);
  
                 DataTable dt = new DataTable();
                 dt = JsonConvert.DeserializeObject<DataTable>(result.Body.loginResult.Data);
  
                 IdentityModel user = new IdentityModel();
                 user.ID = int.Parse(dt.Rows[0]["ID"].ToString());
                 user.Email = dt.Rows[0]["Email"].ToString();
                 user.Role = dt.Rows[0]["Role"].ToString();
                 user.Reg_Date = dt.Rows[0]["Reg_Date"].ToString();
  
                 response.Data = user;
                 response.message = (result.Body.loginResult.resultCode == 500) ? "Login failed.Please check Username and / or password" : "data found";
                 response.code = result.Body.loginResult.resultCode;
             }
             catch (Exception ex)
             {
                 response.code = 500;
                 response.message = ex.Message;
             } 
  
             return response;
         } 

3. Run and Test

Run the IdentityDemo and SoapDemo projects simultaneously. To create a user for you to log in, utilize the register option. Check out my earlier tutorial to get acquainted with the source code utilized here.

Summary

This lesson taught us how to use Dotnet Core to construct and use Soap Web Services. The ASP.NET core project differs from the ASP.NET MVC project in how a soap service is implemented. We can also see that using Visual Studio 2019 to create a Soap Webservice does not come with a project template for an ASMX project; instead, a new component had to be added manually. I sincerely hope that this tutorial will be useful to you and be incorporated into your future projects.

Leave a comment

Your email address will not be published. Required fields are marked *