如何创建一个RESTful WCF Service

简介:

(一)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页面。

image

 

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) };
        }
    }
}
复制代码

 

image

image

image

image

(三)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) };
        }
    }
}
复制代码

 

image

image

image

image

 

(四)总结

  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来设置











本文转自JF Zhu博客园博客,原文链接: http://www.cnblogs.com/jfzhu/p/4044813.html   ,如需转载请自行联系原作者



相关文章
phpstorm插件应用:Test RESTful WEB Service 控制台接口调试工具
phpstorm插件应用:Test RESTful WEB Service 控制台接口调试工具
200 0
|
Oracle 关系型数据库 API
C# LIS检验系统源码,接口技术:RESTful API + Http+WCF
LIS检验系统一种专门用于医院化验室的计算机系统,它致力于提高医院化验室的工作效率和检测准确率。LIS系统由多个子系统组成,包括样本管理系统、质控系统、检验结果管理系统、报告管理系统等。体系结构:Client/Server架构 SaaS模式 客户端:WPF+Windows Forms 服务端:C# +.Net 数据库:Oracle 接口技术:RESTful API + Http+WCF
114 2
|
JSON 缓存 JavaScript
Restful Web Service设计规范
Restful Web Service设计规范
201 0
Restful Web Service设计规范
|
Java Maven Android开发
《Java RESTful Web Service实战》第一章的实现补漏
韩陆,你好你的书,麻烦写的清楚一点,多写一些,也许还能多点稿费。小韩,写书认真一点。第13页上来就用maven命令行创建项目,这就有问题啊,没有pom.xml文件mvn这个命令怎么跑的起来呢?所以正确的过程是这样的:eclipse上创建项目创建的结果是这样的:
1414 0
|
JSON Java 数据格式
搭建一个RESTful Web Service
在搭建之前,首先了解一下什么是RESTful,RESTful(Representational state transfer),它并不是一项新技术,而是一种接口规范。
1698 0
|
Web App开发 JavaScript 前端开发