如何创建一个RESTful WCF Service

原创地址:http://www.cnblogs.com/jfzhu/p/4044813.html

转载请注明出处

 

(一)web.config文件

要创建REST WCF Service,endpoint binding需要用webHttpBinding,参见《webHttpBinding、basicHttpBinding和wsHttpBinding的区别》

web.config

<?xml version="1.0"?>
<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      authentication mode="None" />
    </system.web>
    <system.serviceModel>
        <behaviors>
            <endpointBehaviors>
                <behavior name="SandwichServices.CostServiceBehavior">
                    webHttp helpEnabled="true"/>
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
              <behavior name="SandwichServices.CostServiceServiceBehavior" >
                <serviceMetadata httpGetEnabled="true" />
              </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
            multipleSiteBindingsEnabled="true" />
        <services>
            <service name="SandwichServices.CostService" behaviorConfiguration="SandwichServices.CostServiceServiceBehavior">
                <endpoint address="" behaviorConfiguration="SandwichServices.CostServiceBehavior"
                    binding="webHttpBinding" contract="SandwichServices.CostService" />
              <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
            </service>
        </services>
    </system.serviceModel>
</configuration>

 

《如何创建一个AJAX-Enabled WCF Service》中的web.config,因为需要AJAX,endpointBehaviors用了<enableWebScript />,但是enableWebScript 和REST需要的UriTemplate是有冲突的,所以这里不再使用。

endpointBehaviors中设置<webHttp helpEnabled="true"/>可以生成WCF Service的Help页面。

 

HTTP定义了与服务器交互的不同方法,最基本的方法有4种,分别是GET,POST,PUT,DELETE。一个URL地址,它用于描述一个网络上的资源,而HTTP中的GET,POST,PUT,DELETE就对应着对这个资源的查,改,增,删4个操作。GET一般用于获取/查询资源信息,而POST一般用于更新资源信息。

对于PUT和DELETE,需要身份验证信息,所以我们先暂时只允许匿名访问,在web.config中将authentication mode设置为None。

(二)webHttpBinding的XML格式

Employee.cs

using System;
using System.Runtime.Serialization;

namespace SandwichServices
{
    [DataContract]
    public class Employee
    {
        private Guid id;
        private string name;
        private DateTime birthdate;

        [DataMember]
        public Guid Id
        {
            get { return id; }
            set { id = value; }
        }

        [DataMember]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        [DataMember]
        public DateTime Birthdate
        {
            get { return birthdate; }
            set { birthdate = value; }
        }
    }
}

 

CostService.svc.cs

 

using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace SandwichServices
{
    [ServiceContract(Namespace = "SandwichServices")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CostService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "Employees/AddEmployee", ResponseFormat = WebMessageFormat.Xml)]
        public Guid AddEmployee(Employee employee)
        {
            return Guid.NewGuid();
        }

        [OperationContract]
        [WebInvoke(Method = "DELETE", UriTemplate = "Employees/DeleteEmployee?id={id}", ResponseFormat = WebMessageFormat.Xml)]
        public void DeleteEmployee(string id)
        {
            return;
        }

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "Employees/UpdateEmployee", ResponseFormat = WebMessageFormat.Xml)]
        public void UpdateEmployee(Employee employee)
        {
            return;
        }

        [OperationContract]
        [WebGet(UriTemplate = "Employees/GetEmployee?id={id}", ResponseFormat = WebMessageFormat.Xml)]
        public Employee GetEmployee(string id)
        {
            return new Employee() { Id = new Guid(id), Name = "Neil Klugman", Birthdate = new DateTime(1930, 1, 1) };
        }
    }
}

 

(三)webHttpBinding JSON格式

将每个方法的ResponseFormat改为Json

CostService.svc.cs

 

using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace SandwichServices
{
    [ServiceContract(Namespace = "SandwichServices")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CostService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "Employees/AddEmployee", ResponseFormat=WebMessageFormat.Json)]
        public Guid AddEmployee(Employee employee)
        {
            return Guid.NewGuid();
        }

        [OperationContract]
        [WebInvoke(Method = "DELETE", UriTemplate = "Employees/DeleteEmployee?id={id}", ResponseFormat = WebMessageFormat.Json)]
        public void DeleteEmployee(string id)
        {
            return;
        }

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "Employees/UpdateEmployee", ResponseFormat = WebMessageFormat.Json)]
        public void UpdateEmployee(Employee employee)
        {
            return;
        }

        [OperationContract]
        [WebGet(UriTemplate = "Employees/GetEmployee?id={id}", ResponseFormat = WebMessageFormat.Json)]
        public Employee GetEmployee(string id)
        {
            return new Employee() { Id = new Guid(id), Name = "Neil Klugman", Birthdate = new DateTime(1930, 1, 1) };
        }
    }
}

 

 

(四)总结

  1. RESTful WCF Service需要使用webHttpBinding
  2. endpointBehaviors不要用<enableWebScript />
  3. endpointBehaviors中设置<webHttp helpEnabled="true"/>可以生成WCF Service的Help页面
  4. GET(查),POST(改),PUT(增),DELETE(删)
  5. 对于PUT和DELETE,需要身份验证信息
  6. webHttpBinding的数据格式有两种:XML和JSON,可以通过ResponseFormat来设置
时间: 2024-07-31 12:03:47

如何创建一个RESTful WCF Service的相关文章

如何访问restful wcf service 获取对象集合

问题描述 有个wcfservice,通过添加WebGet,可以通过http://order.svc/getorder?orderid=123这样的方式访问了.interface[WebGet(UriTemplate="GetOrder?orderId={orderId}")]IEnumerable<Order>GetOrder(intorderId);我一直都是通过添加servicereference,然后using(varclient=newOrderServiceCli

jQuery调用RESTful WCF示例代码

 本篇文章主要介绍了jQuery调用RESTful WCF示例代码(GET方法/POST方法),需要的朋友可以过来参考下,希望对大家有所帮助 不废话了,直奔主题吧   wcf端:   近几年比较流行restful,为了能让ajax调用,同时也为了支持restful风格的uri,在创建一个Ajax-enabled Wcf Service后,必须手动修改svc文件,指定Factory,即:   <%@ ServiceHost Language="C#" Debug="tru

jQuery调用RESTful WCF示例(GET方法/POST方法)

不废话了,直奔主题吧 wcf端: 近几年比较流行restful,为了能让ajax调用,同时也为了支持restful风格的uri,在创建一个Ajax-enabled Wcf Service后,必须手动修改svc文件,指定Factory,即: <%@ ServiceHost Language="C#" Debug="true" Service="ajaxSample.HelloWorld" CodeBehind="HelloWorld

jQuery调用RESTful WCF示例代码(GET方法/POST方法)_jquery

不废话了,直奔主题吧 wcf端: 近几年比较流行restful,为了能让ajax调用,同时也为了支持restful风格的uri,在创建一个Ajax-enabled Wcf Service后,必须手动修改svc文件,指定Factory,即: <%@ ServiceHost Language="C#" Debug="true" Service="ajaxSample.HelloWorld" CodeBehind="HelloWorld

[转自雨痕]RESTful WCF

原文:http://www.rainsts.net/article.asp?id=651   REST 最近很热门-- WCF 3.5 增加了对 REST 的支持 -- System.ServiceModel.Web. 对我而言 REST 并不是用来取代 WebService/WCF 的,它更多的是一种架构层面而非技术层面的概念和标准.使用唯一资源定位地址 URI,加上 HTTP 请求方法从而达到对一个发布于互联网资源的唯一描述和操作.这会带来很多好处: 1. 资源的唯一性 对下面这两个 URI

WCF后续之旅(3) WCF Service Mode Layer 的中枢—Dispatcher

在本系列的第一部分.第二部分中,我们对WCF的channel layer进行了深入的讨论.我们接下来继续讨论WCF的service mode layer.本篇文章着重介绍service 端的ServiceMode.写作此篇文章旨在达到以下两个目的: 希望读者对ServiceMode有一个大致的了解,结合前面介绍的channel layer的相关知识,帮助读者了解WCF的整个实现机制和执行的流程. 介绍ServiceMode涉及到的绝大部分extension point,让读者在具体的项目开发中能

jersey (RESTful Web Service框架)

jersey是一个RESTful Web Service框架.web service即远程函数调用,通过该特性,在互联网中跨机器调用其他服务器上的函数,就像调用本地代码一样简单又方便.原理是框架把请求对象序列化为json形式的字符串,发送http请求到指定的服务器上,服务器端把json字符串再反序列化为对象,找到函数代码入口后开始执行,得到返回对象后序列化为json字符串,作为客户端http请求的回应返回,客户端再将结果反序列化为对象.至此,完成一次远程调用.虽然细节上比较麻烦,但框架会帮我们封

WCF后续之旅(13) 创建一个简单的WCF SOAP Message拦截、转发工具

WCF是.NET平台下实现SOA的一种手段,SOA的一个重要的特征就基于Message的通信方式.从Messaging的角度讲,WCF可以看成是对Message进行发送.传递.接收.基础的工具.对于一个消息交换的过程,很多人只会关注message的最初的发送端和最终的接收端.实际上在很多情况下,在两者之间还存在很多的中间结点(Intermediary),这些中间结点在可能在实际的应用中发挥中重要的作用.比如,我们可以创建路由器(Router)进行消息的转发,甚至是Load Balance:可以创

WCF后续之旅(13): 创建一个简单的WCF SOAP Message拦截、转发工具[上篇]

WCF是.NET平台下实现SOA的一种手段,SOA的一个重要的特征就基于Message的通信方式.从Messaging的角度讲,WCF可以看成是对Message进行发送.传递.接收.基础的工具.对于一个消息交换的过程,很多人只会关注message的最初的发送端和最终的接收端.实际上在很多情况下,在两者之间还存在很多的中间结点(Intermediary),这些中间结点在可能在实际的应用中发挥中重要的作用.比如,我们可以创建路由器(Router)进行消息的转发,甚至是Load Balance:可以创