我正在专门寻找一个使用 a) WCF 和 REST 的示例。经过长时间的谷歌搜索,虽然我得到了一些,但它们超出了我的理解。
有人可以给我一个非常简单的例子,比如“Hallow World”或 2 个数字的总和,这将使我清楚地了解如何编写服务器,以及如何从客户端使用它。
另外,如果有任何好的链接可以简单地解释这种示例,请告诉我。
谢谢
最佳答案
一旦你弄清楚了,WCF 中的 REST 并不难。
首先,您必须定义您的界面。
这是一个例子。
[ServiceContract]
public interface IRESTExample
{
[WebGet(UriTemplate = "interaction/queue?s={site}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
string QueueInteraction(string site);
[WebGet(UriTemplate = "interaction/cancel?id={interactionId}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
string CancelInteraction(string interactionId);
[WebGet(UriTemplate = "queue/state?s={site}&q={queue}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
string QueueState(string site, string queue);
}
您可以在 WebGet 中看到您定义的最终 URL。所以这取决于你绑定(bind)它的位置,但是说你将端点绑定(bind)到 www.example.com/rest
QueueInteraciton 将是 www.example.com/rest/interaction/queue?s=SomeSite
其中 {stie} 或 {parameterName} 被替换为参数的名称。
实现只是一个简单的类,我假设你知道如何实现一个接口(interface)。如果您需要帮助,请发表评论。
现在绑定(bind)端点。最后,这并不难,您可以在配置中完成所有操作。
<system.serviceModel>
<services>
<service name="Stackoverflow.Example.Service.RestExample" behaviorConfiguration="MyServiceTypeBehaviors">
<host>
<baseAddresses>
<add baseAddress="http://localhost:2136/RestExample"/>
</baseAddresses>
</host>
<endpoint address="rest" binding="webHttpBinding" behaviorConfiguration="xmlBehavior" contract="Stackoverflow.Example.Service.IRESTExample" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors" >
<!-- Add the following element to your service behavior configuration. -->
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="jsonBehavior">
<webHttp/>
</behavior>
<behavior name="xmlBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name = "NoSecurity">
<security mode = "None" />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
现在是启动服务并绑定(bind)它的代码。你可以在任何事情上做到这一点,例如控制台应用程序。
RestExample exampleService = new RestExample();
host = new ServiceHost(exampleService);
host.Open();
这应该足以开始。
关于wcf - REST 和 WCF 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2277987/