0

I am trying to add an HTTP header in calls to an ASMX service.

Some SO posts talk about SOAP headers, which is not what I want, as that involves adding elements to the body of the POST message, namely this portion:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope ...>
    <soap:Body ...>
        <q2:HeaderIn ...>

What I want is to add to this portion of the request - the HTTP headers:

User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://..."
Host: ...
Content-Length: 2018

To this end I found a post from 2015 which describes adding a Service Reference, choosing the older Web Reference, then selecting a proxy class and overriding GetWebRequest. Unfortunately, in Visual Studio 2017, choosing an alternative proxy class does not appear to be an option. Otherwise, this would have been a great option.

Question: Am I missing something (obvious) which leads to selecting the proxy class for a generated ASMX service client class?

This answer to a similar question (also this one) talks about using OperationContextScope to add custom headers to a WCF request. I figured I could add the service as a WCF service and use this. Converting the solution code from using the generated ASMX client namespace to the generated WCF client was simply a matter of changing the namespaces in the using statements - everything else was the same.

Unfortunately, actually making calls using a WCF client to the ASMX service fails because the generated XML in the request body is completely different.

Question: Am I missing something about using ASMX over WCF which causes this problem or is it simply that it is not possible? (This article would appear to indicate that it is possible.)

Matt W
  • 11,753
  • 25
  • 118
  • 215
  • How do you call the ASMX service(XML web service)? I think there is no difference between a WCF client and a client proxy object. It is the object that initated an Http request. As long as we add an Http header to the proxy object, it should work. On my side, I call the ASMX service by adding service reference(not web reference), subsequently use WebOperationContext which is a convenient wrapper around your above solution, finally get the right HTTP header. – Abraham Qian Feb 06 '20 at 07:03
  • Bizarrely, the generated Service Reference client does not produce the same request body that the Web Reference client does. However, I do have a solution, which does not involve replacing the client class - see my post below. – Matt W Feb 06 '20 at 08:49

1 Answers1

0

Found this post which states that a partial class in a separate file should be used to override GetWebRequest() and insert the custom headers.

Matt W
  • 11,753
  • 25
  • 118
  • 215