Nick Kahn
Nick Kahn

Reputation: 20078

HttpContext null in WCF service?

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

string postData = "username=" + HttpContext.Current.Server.UrlEncode(USERNAME);

Upvotes: 15

Views: 10581

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039408

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);
}

Upvotes: 22

Rob Stevenson-Leggett
Rob Stevenson-Leggett

Reputation: 35689

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

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

Upvotes: 7

Related Questions