如何通过 HTTP Get 使用 WCF 服务(在 Visual Studio 2010 中)

Posted

技术标签:

【中文标题】如何通过 HTTP Get 使用 WCF 服务(在 Visual Studio 2010 中)【英文标题】:How to use a WCF service with HTTP Get (within Visual studio 2010) 【发布时间】:2011-05-15 20:01:14 【问题描述】:

我们尝试使用带有 HTTP Get 的非常简单的 WCF 服务,但无法正常工作。 我们遵循了那些“指南”,但它不起作用

http://msdn.microsoft.com/en-us/library/bb412178.aspx http://www.dotnetfunda.com/articles/article779-simple-5-steps-to-expose-wcf-services-using-rest-style-.aspx

当我们使用以下 url 调用我们的服务时,我们得到一个找不到页面的错误:

http://localhost:9999/Service1.svc/GetData/ABC

基本 url (http://localhost:9999/Service1.svc) 工作正常,并正确返回 wcf 服务信息页面。

这些是重现我们示例的步骤和代码。

    在 Visual Studio 2010 中,创建一个新的“WCF 服务应用程序”项目

    用这段代码替换IService接口

      [ServiceContract()]
      public interface IService1
      
          [OperationContract()]
          [WebInvoke(Method = "GET", 
                     BodyStyle = WebMessageBodyStyle.Bare, 
                     UriTemplate = "GetData/value")]
          string GetData(string value);
      
    

    用此代码替换服务类

    public class Service1 : IService1
    
        public string GetData(string value)
        
            return string.Format("You entered: 0", value);
        
    
    

    web.config 看起来像这样

    <system.web>
       <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
      <services>
          <service name="Service1">
              <endpoint address="" binding="webHttpBinding" contract="IService1" behaviorConfiguration="WebBehavior1">
              </endpoint>
          </service>
      </services>
      <behaviors>
          <endpointBehaviors>
              <behavior name="WebBehavior1">
                 <webHttp helpEnabled="True"/>
        </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    

    按 Run 并尝试调用 Get 方法

如果有人得到这个或类似的工作,如果你能回复有关工作示例的信息,那将是非常友好的。

非常感谢

【问题讨论】:

【参考方案1】:

我重新创建了你的样本 - 就像一个魅力。

一点:您的服务合同 (public interface IService1) 和服务实现 (public class Service1 : IService1) 是否存在于 .NET 命名空间中??

如果是这样,您需要更改您的 *.svc 和您的 web.config 以包括:

<services>
      <service name="Namespace.Service1">
          <endpoint address="" binding="webHttpBinding" 
                    contract="Namespace.IService1" 
                    behaviorConfiguration="WebBehavior1">
          </endpoint>
      </service>
  </services>

&lt;service name="..."&gt; 属性和&lt;endpoint contract="..."&gt; 必须包含 .NET 命名空间才能正常工作。

【讨论】:

你说的非常对...只是因为缺少根命名空间。它适用于其他绑定(没有根命名空间),但不适用于 webHttpBinding。非常感谢。

以上是关于如何通过 HTTP Get 使用 WCF 服务(在 Visual Studio 2010 中)的主要内容,如果未能解决你的问题,请参考以下文章