21

I have a web service (.svc), and I am trying to capture the SOAP request using a piece of code found elsewhere on StackOverflow.

The problem is that HttpContext.Current is null, so I can't access Request.InputString.

Why is this null, and how can it be solved?

XmlDocument xmlSoapRequest = new XmlDocument();

Stream receiveStream = HttpContext.Current.Request.InputStream;
receiveStream.Position = 0;

using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
    xmlSoapRequest.Load(readStream);
}
p.campbell
  • 98,673
  • 67
  • 256
  • 322
Pepito Fernandez
  • 2,352
  • 6
  • 32
  • 47

5 Answers5

50

If you want to use HttpContext because the code has already been written as so; you need to add this to your web.config where your service resides:

<configuration>
    <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    </system.serviceModel>
</configuration>
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • 6
    Thank you. We have prebuilt classes looking for the httpcontext. FYI I also had to add the following preceding my Service class definition --> [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] – ejhost Feb 12 '15 at 20:58
  • Work like a charm! – KumailR Jun 21 '18 at 12:29
  • Worked for me, after long head banging. Thanks a lot !!! – Vikas Nale Jun 08 '22 at 13:05
16

From one of Microsoft's pages on the subject.

HttpContext: Current is always null when accessed from within a WCF service. Use RequestContext instead.

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
2

Correct else use below to read header

 var headers = OperationContext.Current.IncomingMessageProperties["httpRequest"];
                var apiToken = ((HttpRequestMessageProperty)headers).Headers["apiKey"];
Taran
  • 2,895
  • 25
  • 22
0

HttpContext.Current is null when accessed from a web service. Use HttpRuntime.Cache instead.

CAK2
  • 1,892
  • 1
  • 15
  • 17
-4

Please see How to get working path of a wcf application? Use System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath

Community
  • 1
  • 1
Manuel Alves
  • 3,885
  • 2
  • 30
  • 24