Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current is null in my web service

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);
}
like image 941
Pepito Fernandez Avatar asked Jan 23 '12 18:01

Pepito Fernandez


People also ask

Can HttpContext current be null?

Clearly HttpContext. Current is not null only if you access it in a thread that handles incoming requests.

What is HttpContext request?

The Request property provides programmatic access to the properties and methods of the HttpRequest class. Because ASP.NET pages contain a default reference to the System. Web namespace (which contains the HttpContext class), you can reference the members of HttpRequest on an .

How HttpContext is created?

The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.


3 Answers

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>
like image 141
vcsjones Avatar answered Oct 09 '22 04:10

vcsjones


From one of Microsoft's pages on the subject.

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

like image 31
Joachim Isaksson Avatar answered Oct 09 '22 02:10

Joachim Isaksson


Correct else use below to read header

 var headers = OperationContext.Current.IncomingMessageProperties["httpRequest"];
                var apiToken = ((HttpRequestMessageProperty)headers).Headers["apiKey"];
like image 40
Taran Avatar answered Oct 09 '22 02:10

Taran