如何在asp.net中的Windows服务中调用WCF RESTful服务?

时间:2017-01-10 13:56:44

标签: c# asp.net wcf windows-services wcf-rest

我在WCF RESTfule服务中创建了POST方法的操作合同。

IService1.cs: -

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/SaveCustomerPost",
 BodyStyle = WebMessageBodyStyle.Wrapped)]
  string SaveCustomerDetails(CustomerDetails objCustomerDetails);  

[DataContract]
public class CustomerDetails
{
  [DataMember]
  public string Name { get; set; }      
}

Windows服务: -

using (WebChannelFactory<ServiceReference1.IService1> cf = new WebChannelFactory<ServiceReference1.IService1>(new Uri("http://xxx/CustomerService.svc/SaveCustomerPost")))
{
   var helloService = cf.CreateChannel();
   ServiceReference1.CustomerDetails objCustomerDetails = new ServiceReference1.PANNoDetails();
   objPANNoDetails.Name = "TestName";           
   string strResult = helloService.SaveCustomerDetails(objPANNoDetails);
}

客户端App.config: -

<system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="CustBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="WebHttpBinding" sendTimeout="00:05:00" maxBufferSize="2147483647"
          maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
          transferMode="Streamed">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
            maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="None" />
        </binding>
      </webHttpBinding>
    </bindings>
    <client>
      <endpoint address=""
          binding="webHttpBinding" behaviorConfiguration="CustBehavior"
          contract="ServiceReference1.ICustService" name="WebHttpBinding" />
    </client>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0"/>
  </system.serviceModel>

没有端点侦听“xxx.svc / SaveCustomerDetails”可以接受该消息。这通常是由错误的地址或SOAP操作引起的。有关详细信息,请参阅InnerException(如果存在)。

当我在窗口服务中使用WebInvoke方法调用上述方法时,我得到了上述错误。当我调用上面提到的服务没有WebInvoke方法时,服务工作正常。如何解决上述问题?

1 个答案:

答案 0 :(得分:0)

创建ChannelFactory时,请尝试仅指定服务名称:

using (ChannelFactory<ServiceReference1.ICustService> factory = new ChannelFactory<ServiceReference1.ICustService>(
    new WebHttpBinding(),
    "http://xxx/CustomerService.svc"))
{
}