【问题标题】:WCF REST service client calls mapped to wrong UrisWCF REST 服务客户端调用映射到错误的 Uris
【发布时间】:2012-05-23 13:16:53
【问题描述】:

我有一个 WCF REST 服务,很简单,像这样:

[ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [WebInvoke(
           Method = "GET",
           UriTemplate = "getNumber")]
         int GetSomeNumber();
    }

public class TestService : TestServiceApp.ITestService
    {
        public int GetSomeNumber()
        {
            return 5;
        }
    }

是这样配置的:

<services>
      <service name="TestServiceApp.TestService">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="restBehaviour" contract="TestServiceApp.ITestService" />
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="restBehaviour">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

使用指定的 Uri 模板从浏览器调用它可以正常工作:

http://localhost:52602/TestService.svc/getnumber.

我这样配置我的客户端:

 <client>
      <endpoint name="TstSvc" address="http://localhost:52602/TestService.svc" binding="webHttpBinding" contract="TstSvc.ITestService" behaviorConfiguration="restBehaviour"/>
    </client>

  <behaviors>
    <endpointBehaviors>
      <behavior name="restBehaviour">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>

当我使用以下代码调用服务时:

    using (WebChannelFactory<ITestService> factory = new WebChannelFactory<ITestService>("TstSvc"))
    {
        var svc = factory.CreateChannel(); 
        svc.GetSomeNumber();
    }

我得到错误:

"没有端点监听 http://localhost:52602/TestService.svc/GetSomeNumber 可以接受 消息。”

我怀疑由于某种原因,我使用 GetSomeNumber 方法的调用未正确映射到 uri /getnumber。为什么?我该如何解决这个问题,我错过了什么?

【问题讨论】:

    标签: .net wcf rest


    【解决方案1】:

    我能想到的唯一问题是您的ITestService 合约在WebChannelFactory 客户端代码中不是最新的。

    我在测试中确实注意到您在哪里使用WebInvoke 很重要。 WebInvoke 应始终放在您的 ServiceContract接口)上,以便 WebChannelFactory 在通过 REST 通信时具有正确的 URI。如果您将WebInvoke 放在具体类(implementation)上,则WebChannelFactory 默认为OperationContract 名称,如您在上面观察到的。

    【讨论】:

    • 但这不是我想要实现的。您的建议更改了方法本身的名称 - 当它与当然的 uri 相同时,它将起作用。但它不会总是这样,我想知道如果不是这样该怎么办。
    • 你对此有绝对的把握吗?我今天看到一篇关于 cpnsuming twitter 的 rest 服务的文章,他们同时使用 webchannel factory 并且没有匹配的合同名称和 uri (blogs.msdn.com/b/kaevans/archive/2008/07/26/…)。你能提供任何你所说的参考吗?
    • 不 - 你是对的,我的测试有缺陷,请参阅上面的编辑。 WebInvoke 的放置位置对于 WebChannelFactory 正确定位 UriTemplate 很重要。
    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 2016-03-07
    • 2012-05-20
    • 2013-01-19
    • 2010-10-10
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多