c# - 最简单的 REST 服务不工作

标签 c# wcf rest .net-4.0

谁能告诉我为什么这个 REST 服务不起作用?

namespace WCFRestExample
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class HelloWorld : IHelloWorld
    {
        [WebGet(UriTemplate="/", ResponseFormat=WebMessageFormat.Xml)]
        public string GetData()
        {
            return "HIIII";
        }
    }
}

namespace WCFRestExample
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IHelloWorld
    {
        [OperationContract]
        string GetData();
    }
}

这是我的 web.config:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

我能够浏览服务 .svc 并正确获取页面,但是当我浏览时:

http://localhost:60503/HelloWorld.svc/GetData

我得到一个 404 页面。谁能告诉我发生了什么,我在哪里可以找到 WCF REST 的教程?这是一个人可以创建的最简单的服务,即使这样对我也不起作用。

提前致谢:)

最佳答案

你没有在任何地方定义这应该是一个 REST 服务——你的 web.config 中也没有使用 webHttpBinding 的端点,你也没有在你的 * 中指定.svc 文件以使用 WebServiceHostFactory

最简单的修复方法是将 svc 文件修复为:

<%@ ServiceHost Language="C#" Debug="true" 
      Service="WCFRestExample.HelloWorld" CodeBehind="HelloWorld.svc.cs"
       Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

有了这个,您的 svc 文件现在定义它想要使用 WebServiceHost(理解 REST 的主机)来托管您的服务...

查看 An Introduction To RESTful Services With WCF以获得有关使用 WCF 的 REST 服务的精彩介绍。

关于c# - 最简单的 REST 服务不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6815180/

相关文章:

c# - 需要目录中包含今天日期的文件

c# - 是否可以在 IIS 之外的独立应用程序中托管 ASPX 网页

wcf - 如何使用多个 WCF 服务实例强制执行消息队列序列

android - 如何在改造 API 方法中传递 POST 参数?

ruby - 从Docker公开/发布端口

java - @QueryParam 无法获取请求参数

c# - 连接时如何放置取消按钮

c# - SQL语法错误

c# - WCF 服务协定是否可以具有可为 null 的输入参数?

wcf - 客户端应用程序应该使用真实模型类或 DTO 对象与 WCF 服务通信吗?