WCF服务中的HttpContext为null?

Nic*_*ahn 15 c# wcf

这是我的代码行,它引发了我的错误 HttpConext.Current

string postData = "username=" + HttpContext.Current.Server.UrlEncode(USERNAME);
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 22

这很正常.WCF Web服务中没有HTTP上下文.WCF服务甚至可能不在Web服务器中托管.您可以在控制台应用程序内托管.有一个技巧可以让你设置ASP.NET兼容模式:

<system.serviceModel>        
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />    
</system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

但这不是我建议你做的事情.

我会这样做:

var postData = "username=" + HttpUtility.UrlEncode(USERNAME);
Run Code Online (Sandbox Code Playgroud)

因为我对你使用这段代码的方式有了第7个意义(将它作为HTTP请求发送到远程Web服务器)让我们直截了当地说:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "username", USERNAME }
    };
    var result = client.UploadValues("http://foo.com", values);
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*ett 7

如果要启用HttpContext,可以aspNetCompatibilityEnabled在Web配置中设置标志.

<system.serviceModel>        
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />    
</system.serviceModel>
Run Code Online (Sandbox Code Playgroud)