开发者

HttpContext null in WCF service?

开发者 https://www.devze.com 2023-02-14 16:27 出处:网络
here i开发者_如何学JAVAs my line of code and it throws me error on HttpConext.Current string postData = \"username=\" + HttpContext.Current.Server.UrlEncode(USERNAME);

here i开发者_如何学JAVAs my line of code and it throws me error on HttpConext.Current

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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号