Search code examples
c#web-servicessoapasmx

SOAP Exception Removes Custom HTTP Headers


I have a C# ASMX web service (legacy project, can't be helped). One of the requests it has to receive comes with a dynamic HTTP header "TransactionID", and it must be returned in a HTTP header within the response.

When returning success message objects this works fine, however when returning SOAPFault messages all custom HTTP headers are wiped out and I can find no way of restoring them. The client insists it must be sent for failure messages. I've tried using a SOAPExtension, but that has no visibility of HTTP headers. I've tried placing

HttpContext.Current.Response.AddHeader("TransactionID", TransactionId);

in a range of different places, to no avail.

Code below:

[WebMethod(MessageName = "name")]
[SoapHeader("Header")]
[SoapMessageLoggingExtension]
[SoapDocumentMethod("http://www.contoso.com/DocumentLiteral", RequestElementName = "requestName", ResponseElementName = "responseName")]
[return: System.Xml.Serialization.XmlElementAttribute("ReturnType")]
public ResponseType WebMethodName(object RequestObject)
{
    bool success = true;
    int errorType = 0;
    string errorMsg = String.Empty;
    string TransactionId = String.Empty;
    SoapException soapEx = null;

    try
    {
        TransactionId = HttpContext.Current.Request.Headers["TransactionID"].ToString();

        //Determine success or throw appropriate exception
    }
    catch   //example exception
    {
        success = false;
        ErrorType = 1;
        errorMsg = "ErrorText";
        soapEx = new SoapException(_errorType.ToString() + " : " + errorMsg, SoapException.ServerFaultCode);
    }
    finally
    {
        HttpContext.Current.Response.AddHeader("TransactionID", TransactionId);
        if (success)
        {
            resp = new SuccessResponse();
        }
    }

    if (soapEx != null) throw soapEx;
    return resp;
}

I'm at a loss... is this expected behaviour? If so, is there any way around it? Or am I just being dense?

Please let me know if I missed any important information, thanks.


Solution

  • For anyone who encounters this problem in future, I did eventually hack my way around it (with some help from a colleague, credit where it's due).

    I added the header into the response body, then searched for that content in the SoapMessageLoggingExtension once the response was sent, added the HTTP header back in from that and then removed it from the body. Messy, but effective.

    For the record, I still consider this a bug in the framework unless someone can explain why it isn't.