Announcing the ChannelAdam Nancy SOAP Library

My last article introduced the ChannelAdam SOAP Library to make it as easy as possible to create a SOAP 1.1 or SOAP 1.2 payload.

Also as mentioned in that last article, the .NET library Nancy is an excellent lightweight web framework for building HTTP-based web services. While Nancy will not itself ship support for SOAP it still can be used for hosting SOAP web services, if you can create the SOAP payload - and that is exactly what the ChannelAdam SOAP Library helps you do.

However, even after you use the ChannelAdam SOAP Library to build your SOAP payloads, there are still a few hurdles to jump over in order configure Nancy to work with SOAP HTTP requests… until now!

Announcing the release of the open source ChannelAdam Nancy SOAP Library which provides an adapter that makes it as easy as possible to work with SOAP 1.1 and SOAP 1.2 payloads in Nancy.

For information on how to get started, please see the usage documentation.

Enjoy!

The ChannelAdam Nancy SOAP Library

Overview

This is an open source (Apache License 2.0) .NET Standard 2.0 code library that provides functionality for working with SOAP 1.1 and SOAP 1.2 payloads in the lightweight Nancy web framework.

This library builds upon the foundational ChannelAdam Nancy Library and is complemented by:

Getting Started

NuGet Package Installation

To install the ChannelAdam.Nancy.Soap NuGet package run the following command in the Package Manager Console:

1PM> Install-Package ChannelAdam.Nancy.Soap

Usage

Example Hello World SOAP Nancy Module

Below is a simple example of a Nancy Module that defines a handler for a SOAP action.

 1public class HelloWorldSoapNancyModule : NancyModule
 2{
 3    public HelloWorldSoapNancyModule(INancySoapAdapter soapAdapter)
 4    {
 5        const string helloWorldSoapServiceRoutePattern = "/HelloWorldSoap11Service";
 6
 7        // Define the route pattern in Nancy
 8        DefineSoapRoute(helloWorldSoapServiceRoutePattern, soapAdapter);
 9
10        // Register SOAP action handlers for that route pattern
11        soapAdapter.RegisterSoapActionHandler(helloWorldSoapServiceRoutePattern, "urn:HelloWorldSoap11Service#HelloWorldSoapAction",
12            (request, routeArgs) =>
13                Soap11NancyResponseFactory.Create(
14                    SoapBuilder.CreateSoap11Envelope().WithBody.AddEntry("<root>Hello SOAP World!</root>"),
15                    HttpStatusCode.OK));
16
17        // And register more SOAP action handlers for the same route pattern:
18        // soapAdapter.RegisterSoapActionHandler(helloWorldSoapServiceRoutePattern, "urn:HelloWorldSoap11Service#AnotherSoapAction", ...
19    }
20
21    private void DefineSoapRoute(string routePattern, INancySoapAdapter soapAdapter)
22    {
23        Post[routePattern] = args => soapAdapter.ProcessRequest(routePattern, base.Request, args);
24    }
25}

There are three important things going on here:

  1. The ChannelAdam.Nancy.Soap.INancySoapAdapter is injected into the constructor of the Nancy Module class. Nancy’s default bootstrapper will automatically resolve the INancySoapAdapter soapAdapter parameter in the constructor, so you don’t need to be concerned about the constructor injection.

  2. As one normally would do, the route is defined. For a SOAP action, typically that would be done with a HTTP Post. Here is where it gets interesting. For a given route pattern, the action argument to specify is the INancySoapAdapter.ProcessRequest method. This ProcessRequest method on the SOAP Adapter conveniently extracts the SOAP action from either the HTTP header or the SOAP header and then dispatches the request to the corresponding SOAP action handler method that has been registered with it (see the next point).

  3. A SOAP action handler for the same route pattern is registered with the SOAP Adapter. We use the Soap11NancyResponseFactory.Create() method to convert the result of the SoapBuilder (or any string) into a Nancy Response with the appropriate content type for the version of SOAP you are using. Of course, there is also a Soap12NancyResponseFactory helper class for SOAP 1.2 responses.

Example of Self-Hosting Nancy in an Automated Test

Sometimes you want to mock out your actual SOAP services so you can perform Unit Testing instead of Integration Testing. With the ChannelAdam Nancy SOAP Adapter, it is possible to self-host Nancy in the same process as your test case, and just like a mock object, configure it to respond with a specific payload for the current Unit Test.

Below is some dirty automated test code (meant only for this purpose of demonstrating the simplest usage).

Note: I highly recommend following Behaviour-Driven Development practices and the usage of SpecFlow for automated testing.

Step 1 - Identify the Routes and SOAP Actions

The first step is to identify the routes patterns and SOAP actions. Maybe you have these already defined in some constant classes somewhere and if so that’s perfect. For the purpose of this example though, I am putting them into the following static classes.

1public static class TestCaseRoutes
2{
3    public static readonly string MySoap11Service = "/MySoap11Service";
4}
5
6public static class TestCaseSoapActions
7{
8    public static readonly string MySoap11ServiceTestAction = "urn:MySoap11Service#TestAction";
9}

Step 2 - Define a Nancy Module

The next step for an automated test is to create a Nancy Module and define a route.

Unlike the example Hello World Nancy Module above, the difference for an automated test is that within the Nancy Module you would not register the SOAP action handler with the SOAP Adapter (as that will be done later in the test code). The only thing you need to do in the Nancy Module is define the routes.

 1public class TestCaseNancyModule : NancyModule
 2{
 3    public TestCaseNancyModule(INancySoapAdapter soapAdapter)
 4    {
 5        DefineSoapRoute(TestCaseRoutes.MySoap11Service, soapAdapter);
 6    }
 7
 8    private void DefineSoapRoute(string routePattern, INancySoapAdapter soapAdapter)
 9    {
10        Post[routePattern] = args => soapAdapter.ProcessRequest(routePattern, base.Request, args);
11    }
12}

Step 3 - Write the Test Code

Finally the last step is to write the test code.

 1private const string NancyBaseUrl = "http://localhost:8087";
 2
 3private NancySoapAdapter nancySoapAdapter;
 4private NancyHost nancyHost;
 5
 6private string expectedSoapBodyEntryXml;
 7
 8public void SimpleDirtyTestCode()
 9{
10    //------------
11    // Set up
12    //------------
13
14    // Self host Nancy
15    this.nancySoapAdapter = new NancySoapAdapter();
16    this.nancyHost = NancySelfHostFactory.CreateAndStartNancyHostInBackgroundThread(
17        new NancySoapAdapterBootstrapper(this.nancySoapAdapter), 
18        new Uri(NancyBaseUrl));
19
20    //------------
21    // Arrange
22    //------------
23    this.expectedSoapBodyEntryXml = "<root>Whatever you need for this test</root>";
24
25    // Register SOAP action handler for the route pattern
26    soapAdapter.RegisterSoapActionHandler(TestCaseRoutes.MySoap11Service, TestCaseSoapActions.MySoap11ServiceTestAction,
27        (request, routeArgs) =>
28        {
29            // Return a Nancy Response with whatever this specific test case requires...
30            // A SOAP body entry or Soap11NancyResponseFactory.CreateFault()... 
31            return Soap11NancyResponseFactory.Create(
32                SoapBuilder.CreateSoap11Envelope().WithBody.AddEntry(this.expectedSoapBodyEntryXml),
33                HttpStatusCode.OK);
34        });
35    
36    //------------
37    // Act
38    //------------
39    /// TODO - Invoke your System Under Test that will call the Nancy route with the specified SOAP action
40
41    //------------
42    // Assert
43    //------------
44    // TODO - assert the actual response equals this.expectedSoapBodyEntryXml
45    //      - or that a FaultException occurred...
46
47    //------------
48    // Tear Down
49    //------------
50    this.nancyHost.Stop();
51}

The important things to understand are:

  • With the help of the ChannelAdam.Nancy.SelfHosting.NancySelfHostingFactory class, we are self-hosting Nancy in the same process as the test case. Because of this, we specifically create and start it in a background thread so that if the main thread of the test case performs a HTTP request to the route, then everything will respond and be processed as expected.

  • We explicitly create the NancySoapAdapter in the test case and bootstrap it with the NancySoapAdapterBootstrapper into the factory method that creates and starts Nancy. This ensures that the Nancy Module constructor receives the SOAP Adapter instance that we created.

  • Using the NancySoapAdapter, we then register a SOAP action handler specifically returning the response required by the test case.

Reference

NancySoapAdapter & INancySoapAdapter

The ChannelAdam.Nancy.Soap.NancySoapAdapter class which implements the ChannelAdam.Nancy.Soap.Abstractions.INancySoapAdapter interface makes all the magic happen for adapting SOAP payloads to work easily in Nancy.

There are four methods in the interface:

  • Response ProcessRequest(string routePattern, Request request) - this is the action to specify in the Nancy route definition to dispatch the HTTP request to the registered handler for the SOAP action named in the HTTP request header or SOAP header.

  • Response ProcessRequest(string routePattern, Request request, dynamic requestRouteArgs) - this is the action to specify in the Nancy route definition to dispatch the HTTP request to the registered handler for the SOAP action named in the HTTP request header or SOAP header. This overload allows the requestRouteArgs from the route pattern to be provided.

  • void RegisterSoapActionHandler(string routePattern, string soapAction, NancyRequestHandler handler) - registers a handler for the specified route pattern and SOAP action.

  • Request TryWaitForRequest(string routePattern, string soapAction, int retryCount, TimeSpan sleepDuration) - Waits for a specified amount of time for a HTTP request to be received on the specified route with the given SOAP action.

NancySoapAdapterBootstrapper

The NancySoapAdapterBootstrapper is a custom bootstrapper for Nancy.

Normally you don’t need to be concerned with this, but it is especially useful in automated tests.

There are two constructors:

  • public NancySoapAdapterBootstrapper() - which will create a NancySoapAdapter instance for you.

  • public NancySoapAdapterBootstrapper(INancySoapAdapter soapAdapter) - which allows you to specify your own instance of the NancySoapAdapter (which is especially useful in automated tests).

Soap11NancyResponseFactory

The Soap11NancyResponseFactory static class allows you to create a Nancy Response with the correct content type for SOAP 1.1.

There are five methods on the static class:

  • public static Response Create(ISoap11EnvelopeBuilder envelopeBuilder, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified ISoap11EnvelopeBuilder with the correct content type for SOAP 1.1 and with the specified HttpStatusCode.

  • public static Response Create(XContainer soap11Envelope, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified SOAP 1.1 envelope in the XContainer with the correct content type for SOAP 1.1 and with the specified HttpStatusCode.

  • public static Response Create(string soap11EnvelopeXml, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified SOAP 1.1 envelope XML string with the correct content type for SOAP 1.1 and with the specified HttpStatusCode.

  • public static Response CreateFault(ISoap11EnvelopeBuilder envelopeBuilder) - to create a Nancy Response with a SOAP 1.1 fault, as specified by the ISoap11EnvelopeBuilder, with an HttpStatusCode.InternalServerError.

  • public static Response CreateFault(XContainer envelope) - to create a Nancy Response with a SOAP 1.1 fault, as specified by the SOAP 1.1 envelope in the specified XContainer, with an HttpStatusCode.InternalServerError.

Soap12NancyResponseFactory

The Soap12NancyResponseFactory static class allows you to create a Nancy Response with the correct content type for SOAP 1.2. This is the SOAP 1.2 equivalent of the Soap11NancyResponseFactory.

There are five methods on the static class:

  • public static Response Create(ISoap12EnvelopeBuilder envelopeBuilder, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified ISoap11EnvelopeBuilder with the correct content type for SOAP 1.2 and with the specified HttpStatusCode.

  • public static Response Create(XContainer soap12Envelope, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified SOAP 1.2 envelope in the XContainer with the correct content type for SOAP 1.2 and with the specified HttpStatusCode.

  • public static Response Create(string soap12EnvelopeXml, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified SOAP 1.2 envelope XML string with the correct content type for SOAP 1.2 and with the specified HttpStatusCode.

  • public static Response CreateFault(ISoap12EnvelopeBuilder envelopeBuilder) - to create a Nancy Response with a SOAP 1.2 fault, as specified by the ISoap11EnvelopeBuilder, with an HttpStatusCode.InternalServerError.

  • public static Response CreateFault(XContainer envelope) - to create a Nancy Response with a SOAP 1.2 fault, as specified by the SOAP 1.2 envelope in the specified XContainer, with an HttpStatusCode.InternalServerError.

SoapNancyRequestHelper

The SoapNancyRequestHelper static class provides helpful functionality that operates on a Nancy Request.

There is one method on the static class:

  • public static string GetSoapAction(Request request) - to retrieve the SOAP action from either the HTTP header or the SOAP envelope header. The HTTP header takes precedence.

This functionality is also surfaced as an extension method on the Nancy Request class for which you will need a using statement for ChannelAdam.Nancy.Soap.

Announcing the ChannelAdam SOAP Library

The Simple Object Access Protocol (SOAP) has been around for more than a decade. While HTTP-based API’s and RESTful services are the current trend, SOAP web services are still the rock bed of most businesses and contemporary systems.

On-premises API gateways such as the CA API Gateway has had support for publishing SOAP web services for quite a while.

In fact, there is still such demand in the industry for integration with SOAP services that Microsoft’s newer cloud-based Azure API Management service also now has the capability to publish SOAP API’s.

The .NET library Nancy is an excellent lightweight web framework for building HTTP-based web services. While Nancy will not itself ship support for SOAP it still can be used for hosting SOAP web services, if you can create the SOAP payload.

Libraries such as Nancy or Mock4Net (a tiny mock HTTP server for .NET) can be used in automated Unit Tests to dynamically create mock web services that return the exact response required for each specific test case. In fact, I personally use this specific technique to perform advanced Unit Testing of black-box code artefacts such as BizTalk orchestrations.

However, creating and composing a SOAP envelope, header, and body or fault has always been a tricky undertaking, and unless you have studied the SOAP specifications in detail and use them daily, it is easy to either forget or confuse the differences between SOAP 1.1 and SOAP 1.2 - that is, until now!

Introducing the ChannelAdam SOAP Library – a fluent .NET API to make it as easy as possible to create a SOAP 1.1 or SOAP 1.2 payload.

For information on how to get started, please see the usage documentation.

You might also be interested in the ChannelAdam Nancy SOAP Library which makes using SOAP with Nancy even easier.

The ChannelAdam SOAP Library

Overview

This is an open source (Apache License 2.0) .NET Standard 2.0 code library that provides a fluent API to make it as easy as possible to create a SOAP 1.1 or SOAP 1.2 message.

Among other things, it is perfect for building SOAP envelopes to use in lightweight web frameworks such as Nancy.

Getting Started

NuGet Package Installation

To install the ChannelAdam.Soap NuGet package run the following command in the Package Manager Console:

1PM> Install-Package ChannelAdam.Soap

Usage

There are plenty of overloads and other methods for more advanced usage - see the reference in the next section.

SOAP Envelope with a Header Action and Body

Here is a simple example of creating a SOAP 1.1 envelope with a header action and body payload.

1string envelopeXml = SoapBuilder.CreateSoap11Envelope()
2    .WithHeader.AddAction("http://my.action/here")
3    .WithBody.AddEntry("<myXml>hello from the body</myXml>")
4    .Build()
5    .ToString();

And for SOAP 1.2:

1string envelopeXml = SoapBuilder.CreateSoap12Envelope()
2    .WithHeader.AddAction("http://my.action/here")
3    .WithBody.AddEntry("<myXml>hello from the body</myXml>")
4    .Build()
5    .ToString();

There is even an overload to create the body entry from .NET objects. For instance:

 1public class MyModel
 2{
 3    public string Value { get; set; } 
 4}
 5
 6...
 7
 8var model = new MyModel { Value = "hello!" };
 9
10string envelopeXml = SoapBuilder.CreateSoap12Envelope()
11    .WithHeader.AddAction("http://my.action/here")
12    .WithBody.AddEntry(model)
13    .Build()
14    .ToString();

Easy!

SOAP Faults

To create a SOAP 1.1 fault:

1string envelopeXml = SoapBuilder.CreateSoap11Envelope()
2    .WithBody.SetFault(Soap11FaultCode.Client, "SOAP 1.1 fault string here")
3    .Build()
4    .ToString();

And for a SOAP 1.2 fault:

1string envelopeXml = SoapBuilder.CreateSoap11Envelope()
2    .WithBody.SetFault(Soap12FaultCode.Sender, "SOAP 1.2 fault reason here")
3    .Build()
4    .ToString();

There are overloads to set other SOAP fault value properties as well.

Reference

This reference assumes that the reader is familiar with SOAP terminology. For more information see the following SOAP specifications:

SoapBuilder

The SoapBuilder static class is the fluent starting point for building a SOAP 1.1 or SOAP 1.2 envelope.

The SoapBuilder static class has two methods:

  • ISoap11EnvelopeBuilder CreateSoap11Envelope() - to start the process of creating a SOAP 1.1 envelope

  • ISoap12EnvelopeBuilder CreateSoap12Envelope() - to start the process of creating a SOAP 1.2 envelope

The ISoap11EnvelopeBuilder interface has two properties and one method:

  • ISoap11BodyBuilder WithBody { get; } - to specify the SOAP body or a fault

  • ISoap11HeaderBuilder WithHeader { get; } - to specify the SOAP header

  • XContainer Build() - to finally build the SOAP envelope as specified

The ISoap12EnvelopeBuilder interface is similar:

  • ISoap12BodyBuilder WithBody { get; }

  • ISoap12HeaderBuilder WithHeader { get; }

  • XContainer Build()

Usage of SoapBuilder

The general procedure for usage is:

  1. Call one of the SoapBuilder.CreateSoap??Envelope() methods.

  2. If necessary, add a header via the WithHeader property.

  3. Add a body or fault message via the WithBody property.

  4. Once all the details have been specified, simply call the Build() method which will return an XContainer.

  5. If there is something that you need to do to the contents of the SOAP envelope that is not currently allowed by the API, then you can always directly modify the elements in the XContainer and do magical things with LINQ.

  6. A simple .ToString() on the XContainer returned from Build() will then give you the XML string of the SOAP envelope/payload - by default formatted with indentation. There is also the overload .ToString(System.Xml.Linq.SaveOptions options) that allows you to change the formatting of whitespace and indentation.

Specify the SOAP Header

The SOAP header can be specified via the WithHeader property.

For SOAP 1.1, WithHeader chains the following methods:

1ISoap11EnvelopeBuilder AddAction(string action);
2
3ISoap11EnvelopeBuilder AddBlock(string headerXml);
4ISoap11EnvelopeBuilder AddBlock(XContainer headerBlock);
5ISoap11EnvelopeBuilder AddBlock(object toSerialise);
6ISoap11EnvelopeBuilder AddBlock(object toSerialise, string toElementName, string toElementNamespace);
7
8ISoap11EnvelopeBuilder SetStandardSoapEncoding();
9ISoap11EnvelopeBuilder SetCustomSoapEncoding(string soapEncodingNamespace);

Notes:

  • AddAction(string action) adds an action header block with the specified action.
  • AddBlock(XContainer headerBlock) adds any arbitrary header block - e.g. from a System.Xml.Linq.XElement.
  • AddBlock(object toSerialise, string toElementName, string toElementNamespace) serialises the given object and during serialisation overrides the XML element name and namespace with those specified.
  • ISoap11EnvelopeBuilder SetStandardSoapEncoding() sets the SoapEncoding attribute to the standard encoding namespace
  • ISoap11EnvelopeBuilder SetCustomSoapEncoding(string soapEncodingNamespace) sets the SoapEncoding attribute to your custom namespace

For SOAP 1.2, WithHeader is nearly identical to SOAP 1.1, except an ISoap12EnvelopeBuilder is returned instead of a ISoap11EnvelopeBuilder.

Specify the SOAP Body Payload or Fault

The SOAP body payload or fault can be specified via the WithBody property which provides the following methods.

For SOAP 1.1

 1ISoap11EnvelopeBuilder AddEntry(string bodyXml);
 2ISoap11EnvelopeBuilder AddEntry(XContainer fromNode);
 3ISoap11EnvelopeBuilder AddEntry(object toSerialise);
 4ISoap11EnvelopeBuilder AddEntry(object toSerialise, string toElementName, string toElementNamespace);
 5
 6ISoap11EnvelopeBuilder SetFault(Soap11FaultCode code, string faultString);
 7ISoap11EnvelopeBuilder SetFault(Soap11FaultCode code, string faultString, string faultActor);
 8ISoap11EnvelopeBuilder SetFault(Soap11FaultCode code, string faultString, string faultActor, IEnumerable<XContainer> detailEntries);
 9
10ISoap11EnvelopeBuilder SetStandardSoapEncoding();
11ISoap11EnvelopeBuilder SetCustomSoapEncoding(string soapEncodingNamespace);

Notes:

  • AddEntry(object toSerialise, string toElementName, string toElementNamespace) serialises the given object and during serialisation overrides the XML element name and namespace with those specified.

SOAP 1.2 Faults are more descriptive than SOAP 1.1, hence the overloads of SetFault with more parameters.

For SOAP 1.2

 1ISoap12EnvelopeBuilder AddEntry(string bodyXml);
 2ISoap12EnvelopeBuilder AddEntry(XContainer fromNode);
 3ISoap12EnvelopeBuilder AddEntry(object toSerialise);
 4ISoap12EnvelopeBuilder AddEntry(object toSerialise, string toElementName, string toElementNamespace);
 5
 6ISoap12EnvelopeBuilder SetFault(Soap12FaultCode code, string reason);
 7ISoap12EnvelopeBuilder SetFault(Soap12FaultCode code, string subCode, string reason);
 8ISoap12EnvelopeBuilder SetFault(Soap12FaultCode code, XNamespace subCodeNamespace, string subCode, string reason);
 9ISoap12EnvelopeBuilder SetFault(Soap12FaultCode code, XNamespace subCodeNamespace, string subCode, string reason, string reasonXmlLanguage);
10ISoap12EnvelopeBuilder SetFault(Soap12FaultCode code, XNamespace subCodeNamespace, string subCode, string reason, string reasonXmlLanguage, string node);
11ISoap12EnvelopeBuilder SetFault(Soap12FaultCode code, XNamespace subCodeNamespace, string subCode, string reason, string reasonXmlLanguage, string node, string role);
12ISoap12EnvelopeBuilder SetFault(Soap12FaultCode code, XNamespace subCodeNamespace, string subCode, string reason, IEnumerable<XContainer> detailEntries);
13ISoap12EnvelopeBuilder SetFault(Soap12FaultCode code, XNamespace subCodeNamespace, string subCode, string reason, string reasonXmlLanguage, IEnumerable<XContainer> detailEntries);
14ISoap12EnvelopeBuilder SetFault(Soap12FaultCode code, XNamespace subCodeNamespace, string subCode, string reason, string reasonXmlLanguage, string node, string role, IEnumerable<XContainer> detailEntries);
15
16ISoap12EnvelopeBuilder SetStandardSoapEncoding();
17ISoap12EnvelopeBuilder SetCustomSoapEncoding(string soapEncodingNamespace);