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

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

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

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

Need Your Help

How to clone a specific branch in git bitbucket

git github bitbucket git-svn

I want to clone a specific branch. I don't want download the master branch.