使用HttpClient调用WCF服务

7

我需要调用一个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;

        }
    }

服务器端代码:
    [ServiceContract]
    public interface IAttempts
    {
        [OperationContract]
        void ReceiveAttemptResult(ReceiveAttemptResultInput result);
    }

    public class Attempts : IAttempts
    {
        string _backendUrl;

        public void ReceiveAttemptResult(ReceiveAttemptResultInput result)
        {
           //...
        }
    }

最后,在服务器端进行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>

当我调用该服务时,我只得到了一个空字符串,并且无法在服务内部进行调试... 这是怎么回事呢?
谢谢。

您的终端点URL似乎不完整。 它应该类似于:http://localhost:52937/Attempts.svc/Endpoint - Oluwafemi
我已将URL更改为以下内容:http://localhost:52937/PaymentAttempts.svc/ReceiveAttemptResult,但仍然没有任何变化:( - Simone
4
为了未来读者的方便,我运行了WcfTestClient并查看了它发送的HTTP头。因此,我添加了 httpClient.DefaultRequestHeaders.Add("SOAPAction", "TheSameAsIn_WcfTestClient")并且它工作正常! - Disappointed
1个回答

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接