使用 HttpClient 调用 WCF 服务

Cic*_*cio 6 c# wcf httpclient

我必须调用 WCF 服务。WCF 服务已开启,我可以编辑其配置。

我想创建一个调用服务的客户端。我无法将服务引用添加到我的客户端,因此我尝试使用 HttpClient 调用它。

客户端代码:

    using (var client = new HttpClient())
    {
        //soapString is my input class serialized
        var content = new StringContent(soapString, Encoding.UTF8, "text/xml");
        using (var postResponse = client.PostAsync("http://localhost:52937/Attempts.svc/", content).Result)
        {
            string postResult = postResponse.Content.ReadAsStringAsync().Result;

        }
    }
Run Code Online (Sandbox Code Playgroud)

服务器端代码:

    [ServiceContract]
    public interface IAttempts
    {
        [OperationContract]
        void ReceiveAttemptResult(ReceiveAttemptResultInput result);
    }

    public class Attempts : IAttempts
    {
        string _backendUrl;

        public void ReceiveAttemptResult(ReceiveAttemptResultInput result)
        {
           //...
        }
    }
Run Code Online (Sandbox Code Playgroud)

最后是 web.config 服务器端:

    <system.serviceModel>
      <services>
        <service name="it.MC.Listeners.Attempts">
          <endpoint address="" contract="it.MC.Listeners.IAttempts" binding="basicHttpBinding"/>
          <endpoint address="mex" contract="IMetadataExchange" binding="mexHttpBinding"/>
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="">
            <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
            <serviceDebug includeExceptionDetailInFaults="false" />
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

当我调用该服务时,我只是获得了一个空字符串,并且无法在服务内部进行调试...有什么问题?

谢谢

Tom*_*gan 1

以防万一这会困扰其他人。谢谢@Disappointed 丢失的拼图,它促使我在打开 Fiddler 的 WCF 测试客户端中运行该东西,看看我丢失了什么:

    HttpClient httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://tempuri.org/IMyService/Mymethod_Async");
    string soapEnvelope = "<s:Envelope xmlns:s= \"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><Mymethod_Async xmlns=\"http://tempuri.org/\"/></s:Body></s:Envelope>";
    var content = new StringContent(soapEnvelope, Encoding.UTF8, "text/xml");
    HttpResponseMessage hrm = httpClient.PostAsync("http://MyService.MyDomain.com/MyService.svc", content).Result;
Run Code Online (Sandbox Code Playgroud)