我为此奋斗了好几个小时,直到我最终使用了这个示例并且它首先成功了:http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide
我知道只有链接的答案不好,其他人已经使用此 CP 链接到 solve this type of problem here at Stackoverflow 所以如果文章失败,以下是基本步骤:
第 1 步
首先启动 Visual Studio 2010。单击 FILE->NEW->PROJECT。创建新的“WCF 服务应用程序”。
第 2 步
创建项目后,您可以在解决方案中看到默认情况下已创建 WCF 服务和接口文件(Service1.cs 和 IService.cs)。删除这两个文件,我们将创建自己的接口和 WCF 服务文件。
第 3 步
现在右键单击解决方案并创建一个新的 WCF 服务文件。我已将服务文件命名为“RestServiceImpl.svc”。
第 4 步
正如我在文章开头所解释的,我们将编写一个可以返回 XML 和 JSON 格式数据的 API,这里是它的接口。在IRestServiceImpl中,添加如下代码
在上面的代码中,您可以看到 IRestService 的两种不同方法,即 XMLData 和 JSONData。 XMLData 以 XML 形式返回结果,而 JSONData 以 JSON 形式返回。
[ServiceContract]
public interface IRestServiceImpl
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "xml/{id}")]
string XMLData(string id);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/{id}")]
string JSONData(string id);
}
第 5 步
打开文件 RestServiceImpl.svc.cs 并在其中编写以下代码:
public class RestServiceImpl : IRestServiceImpl
{
public string XMLData(string id)
{
return "You requested product " + id;
}
public string JSONData(string id)
{
return "You requested product " + id;
}
}
第 6 步
Web.Config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="RestService.RestServiceImpl" behaviorConfiguration="ServiceBehaviour">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address ="" binding="webHttpBinding" contract="RestService.IRestServiceImpl" behaviorConfiguration="web">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
第七步
在 IIS 中: