here is my line of code and it throws me error on HttpConext.Current
string postData = "username=" + HttpContext.Current.Server.UrlEncode(USERNAME);
Clearly HttpContext. Current is not null only if you access it in a thread that handles incoming requests.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With