DEV Community

Janki Mehta
Janki Mehta

Posted on

Create SOAP Services Using ASP.NET Core

SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs built with different languages and on different platforms to communicate using XML. SOAP services provide a way to expose backend functionality over the web using the SOAP messaging framework.

In this blog post, we will see how to create and consume SOAP web services in ASP.NET Core. We will learn how to:

Enable SOAP services support in ASP.NET Core

  • Create a SOAP web service
  • Add SOAP endpoints
  • Secure SOAP endpoints
  • Host and test SOAP services
  • Consume SOAP services in client applications

Enabling SOAP Services in ASP.NET Core

Unlike ASP.NET 4.x that has built-in support for SOAP-based web services through ASMX, ASP.NET Core does not include SOAP services capability out of the box.

We need to take help of a third-party library called System.ServiceModel.Primitives to build SOAP-based services in ASP.NET Core.

To add SOAP services support, first install the NuGet package:

Install-Package System.ServiceModel.Primitives
Enter fullscreen mode Exit fullscreen mode

This package contains the necessary types and interfaces to expose and consume SOAP services. The next sections show how to build on top of this to create SOAP endpoints.

Creating a SOAP Web Service
Let's create a simple SOAP web service with one operation to get customer details by ID.

First, create an interface representing the service contract:

public interface ICustomerService
{
    Customer GetCustomer(int id); 
}

public class Customer 
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Next, implement this interface:

public class CustomerService : ICustomerService
{
    public Customer GetCustomer(int id)
    {
        // Logic to fetch data from database and return Customer
    }
}
Enter fullscreen mode Exit fullscreen mode

This simple service is now ready to be exposed over SOAP.

Exposing SOAP Endpoints

ASP.NET Core does not include SOAP endpoint support out of the box. So we need to configure that ourselves.

Install the NuGet package - Microsoft.AspNetCore.WebApi.WebHost

This will allow hosting web APIs on top of HTTP servers like IIS or IIS Express.

In Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddWebApi();

    services.AddScoped<ICustomerService, CustomerService>(); 

    services.AddSoapCore();
}

public void Configure(IApplicationBuilder app)  
{
    app.UseSoapEndpoint<ICustomerService>("/CustomerService.asmx", new BasicHttpBinding(), SoapSerializer.DataContractSerializer);
}
Enter fullscreen mode Exit fullscreen mode

The AddSoapCore method comes from SoapCore library that does the heavy-lifting of mapping SOAP messages over HTTP.

And UseSoapEndpoint maps the specified interface to the SOAP endpoint, with binding and serialization set up.

We can now access the SOAP service using HTTP requests like any REST API. The next section shows how to test this.

Testing the SOAP API
Let's test our SOAP API using SoapUI or Postman.

A sample request XML looks like:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:GetCustomer>
         <tem:id>1</tem:id>
      </tem:GetCustomer>
   </soapenv:Body>
</soapenv:Envelope>
Enter fullscreen mode Exit fullscreen mode

And response like:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <GetCustomerResponse xmlns="http://tempuri.org/">
      <Customer>
        <Id>1</Id>
        <Name>John</Name>
      </Customer>
    </GetCustomerResponse>
  </s:Body>
</s:Envelope>
Enter fullscreen mode Exit fullscreen mode

We can send requests and view responses either in SoapUI or using Postman. This confirms our service is working as expected.

Securing SOAP Services

Since SOAP services expose backend application logic, it is important to secure access to them. Some ways to secure SOAP services include:

1. Transport-Level Security using HTTPS

Require SSL and allow requests only using HTTPS protocol.

2. Message-Level Security

Use WS-Security to encrypt SOAP requests and responses.

3. Authentication and Authorization

Validate sender identity using security tokens or API keys before processing requests.

This ensures that only authorized clients can access the SOAP API.

Here is an example to secure the service using API key authentication:

// Validate API Key existence
if(!Request.Headers.Contains("X-API-Key")) 
    throw new Exception("Unauthorized");

// Check if API Key is valid
if(!IsAPIKeyValid(Request.Headers["X-API-Key"])) 
    throw new Exception("Forbidden");

// Allow request
Enter fullscreen mode Exit fullscreen mode

We can implement other authentication mechanisms like OAuth as well.

Hosting ASP.NET Core SOAP Services

To host the SOAP web service, configure the ASP.NET Core app to use the IIS/IIS Express hosting model:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseIIS();
Enter fullscreen mode Exit fullscreen mode

Alternatively, we can self-host the service using Kestrel.

For production use, hosting behind IIS with transport security is recommended.

Consuming SOAP Web Services
To consume ASP.NET Core SOAP web services from a .NET client:

  • Add service reference to client project
  • Generate proxy client code
  • Create client instance and invoke service operations For example:
// 1. Add service reference 

// 2. Generate proxy
var client = new CustomerServiceClient();  

// 3. Call operation
var customer = client.GetCustomer(1);
Enter fullscreen mode Exit fullscreen mode

The service reference handles all serialization/deserialization and communication with the SOAP endpoint.

For Java or other language clients, we can consume the ASP.NET Core SOAP service by generating client code using the wsdl file.

Last Words

In this post, we learned how to build and expose SOAP web services in ASP.NET Core using the SoapCore library. Some of the key things we covered:

  • Adding NuGet packages for SOAP support
  • Creating service interfaces and implementation
  • Configuring SOAP endpoint routing
  • Testing SOAP API using SoapUI/Postman
  • Securing services with authentication and HTTPS
  • Hosting SOAP services in IIS
  • Consuming from .NET clients

SOAP services allow exposing backend application logic in a standardized way. Integrating them securely into modern web apps allows reusing existing systems.

Hope this gives you a good overview of building SOAP-based services in ASP.NET Core web applications!

Source: How to Create SOAP Services Using ASP.NET Core?

Top comments (0)