如何創建一個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頁面。

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來設置

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM