如果将WCF服务发布为rest模式

   WCF是支持多种协议的,其中basicHttpBinding是基础协议绑定,类似于传统的webservice。

   如果要将WCF发布成rest,绑定协议要使用webHttpBinding,并且在终结点的绑定中设置behavior增加webhttp协议。

   具体的做法为:

   1、在interface的服务方法上,添加WebInvoke

  

[OperationContract]
        [WebInvoke(Method = "POST",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/Test/Save"
         )]
        string TestSave(TestSaveRequest requestmessage);

 这里注意,需要将该接口下所有的方法都需要加上WebInvoke,不然会报错。

  2、在配置文件中

  

在节点services中
<service name="Test.TestSvc" behaviorConfiguration="serviceBehavior">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="web"
          contract="Test.ITestSvc" />
      </service>
重要的是binding="webHttpBinding"    behaviorConfiguration="web"



在节点behaviors中插入
<endpointBehaviors>
         <behavior name="web">
            <webHttp/>
        </behavior>
      </endpointBehaviors>

这是根据配置文件处理的方式。

有时候我们需要用代码来代替配置文件,也是很简单的

下面是代码实现该配置

System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(ITestSvc), new Uri(baseserviceurl));
            WebHttpBinding binding = new WebHttpBinding();
            //ServiceEndpoint end;
            //end.Contract
            //由于 ContractFilter 在 EndpointDispatcher 不匹配,因此 Action 为“”的消息无法在接收方处理。这可能是由于协定不匹配(发送方和接收方 Action 不匹配)或发送方和接收方绑定/安全不匹配。请检查发送方和接收方是否具有相同的协定和绑定(包括安全要求,如 Message、Transport、None)
            var endpoint = host.AddServiceEndpoint(typeof(ITestSvc), binding, "");
            // [System.ServiceModel.Description.WebHttpBehavior] = {System.ServiceModel.Description.WebHttpBehavior}
            endpoint.Behaviors.Add(new WebHttpBehavior());

实现了rest方式以后,传统的直接引用调用也是可以同时使用的,所以还是非常的方便的。

最后切记一点,UriTemplate的路径中,除非只有一级,不然不能有一段和方法名完全一致,不然会出现调用错误。如果UriTemplate = "Test/Go",方法名为Go,就会出现rest调用错误。

转载于:https://www.cnblogs.com/guoyc/p/5262147.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值