谁能告诉我为什么这个 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/