Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext null in WCF service?

Tags:

c#

wcf

here is my line of code and it throws me error on HttpConext.Current

string postData = "username=" + HttpContext.Current.Server.UrlEncode(USERNAME);
like image 790
Nick Kahn Avatar asked Mar 04 '11 14:03

Nick Kahn


People also ask

Can HttpContext request 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 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.


2 Answers

That's normal. There is no HTTP Context in a WCF web service. A WCF service might not even be hosted inside a web server. You could host in inside a console application. There's a trick that allows you to set the ASP.NET Compatibility Mode:

<system.serviceModel>        
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />    
</system.serviceModel>

but it is not something that I would recommend you doing.

I would do this instead:

var postData = "username=" + HttpUtility.UrlEncode(USERNAME);

And because I have a 7th sense about where you are going with this code (sending it as an HTTP request to a remote web server) let's get straight to the point:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "username", USERNAME }
    };
    var result = client.UploadValues("http://foo.com", values);
}
like image 177
Darin Dimitrov Avatar answered Sep 29 '22 04:09

Darin Dimitrov


If you want to enable the HttpContext you can set the aspNetCompatibilityEnabled flag in web config.

<system.serviceModel>        
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />    
</system.serviceModel>
like image 35
Rob Stevenson-Leggett Avatar answered Sep 29 '22 02:09

Rob Stevenson-Leggett