Access XML Header using SOAPCore

1.1k views Asked by At

I'm using SoapCore 1.1.0.8 with .NetCore 3.1

Does anyone know how to access the XML header from an envelope using SoapCore?

For example, an envelope like the following

    <SOAP:Header xmlns='http://www.acompany.com/gsd'>
        <ns0:AuthenticationInfo xmlns:ns0='http://customheader.com'>
            <ns0:userName>Dummy_User</ns0:userName>
            <ns0:password>Dummy_Pwd</ns0:password>
        </ns0:AuthenticationInfo>
    </SOAP:Header>
    <SOAP:Body xmlns='http://www.acompany.com/gsd'>
        <MsgReq xmlns='http://www.acompany.com/gsd' xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
            <MethodName>Identify</MethodName>
            <MethodID>IS_001_01</MethodID>
.
.
        </MsgReq>
    </SOAP:Body>
</SOAP:Envelope>

How could you access the userName and password elements?

1

There are 1 answers

0
Matija Sestak On

You can access to XML header by using IServiceOperationTuner.

public class ServiceOperationTuner : IServiceOperationTuner
    {
        public void Tune(HttpContext httpContext, object serviceInstance, OperationDescription operation)
        {
            if (serviceInstance is YourServiceClass)
            {
                YourServiceClass)service = serviceInstance as YourServiceClass)
                service.SetHttpRequest(httpContext.Request);
            }
        }
    }

After that register ServiceOperationTuner in Startup.cs.

        public void ConfigureServices(IServiceCollection services)
        {
...
            services.AddSoapServiceOperationTuner(new ServiceOperationTuner());
...
        }

In your service add

  private ThreadLocal<HttpRequest> _httpRequest = new() { Value = null };

        public void SetHttpRequest(HttpRequest request)
        {
            _httpRequest.Value = request;
        }

And after that you can get RAW Soap Header XML from HttpContext

        private XmlNode GetHeaderFromRequest(HttpRequest request)
        {
            var bytes = (request.Body as MemoryStream)?.ToArray();
            if (bytes == null)
            {
                // Body missing from request
                return null;
            }

            var envelope = new XmlDocument();
            envelope.LoadXml(Encoding.UTF8.GetString(bytes));

            return envelope.DocumentElement?.ChildNodes.Cast<XmlNode>().FirstOrDefault(n => n.LocalName == "Header");
        }