簡單五步創建一個WCF Rest Service

1、創建一個WCF Service Application



2、創建一個實體對象Student,用作數據傳輸的載體,下面是Student.cs的內容

using System.Runtime.Serialization;
namespace WCFRest
{
    /// <summary>
    /// DataContract 數據契約:服務端和客戶端之間要傳送的自定義數據類型
    /// </summary>
    [DataContract]
    public class Student
    {
        /// <summary>
        /// 在數據傳送過程中,只有成員變量可以被傳送而成員方法不可以。
        /// 並且只有當成員變量加上DataMember時纔可以被序列進行數據傳輸,
        /// 如果不加DataMember,客戶端將無法獲得該屬性的任何信息
        /// </summary>
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
    }
}

同時我們創建一個類,用來模擬數據庫的存儲

using System.Collections.Generic;

namespace WCFRest
{
    public class UserList
    {
        private static readonly UserList _Instance = new UserList();
        private UserList() { }

        public static UserList Instance
        {
            get { return _Instance; }
        }

        public IList<Student> Users
        {
            get { return _Users; }
        }

        private IList<Student> _Users = new List<Student>{
            new Student {Id = 1, Name = "張三" },
            new Student {Id = 2, Name = "李四" },
            new Student {Id = 3, Name = "王五" }
        };
    }
}


3、創建服務契約

下面我們在項目添加一個WCF Service


首先修改IStudnetService接口,配置Rest的URL路徑

using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace WCFRest
{
    [ServiceContract]
    public interface IStudentService
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "GetStudentById/Id={Id}"
         )]
        Student GetStudentById(string Id);

        [OperationContract]
        [WebInvoke(Method = "GET",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "GetStudentList"
         )]
        IList<Student> GetStudentList();
    }
}

4、修改StudentService類,實現Rest方法

using System.Collections.Generic;

namespace WCFRest
{
    public class StudentService : IStudentService
    {
        
        public Student GetStudentById(string Id)
        {
            return StudentList.Instance.Users[int.Parse(Id)];
        }

        public IList<Student> GetStudentList()
        {
            return StudentList.Instance.Users;
        }
    }
}

5、配置Service和Behavior

在Web.Config中配置我們的Rest服務

 <system.serviceModel>
    <services>
      <service name="WCFRest.StudentService" behaviorConfiguration="serviceBehavior">
        <endpoint address="" binding="webHttpBinding" contract="WCFRest.IStudentService" 
                  behaviorConfiguration="web"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

OK,下面測試一下我們的程序,右擊Student.svc文件,選擇View In Browser,我們將會看到下面的運行結果



然後我們在url後面加上我們定義的Rest地址就可以訪問Rest服務了





說明:本文絕大部分內容摘自下面文章

http://www.topwcftutorials.net/2013/09/simple-steps-for-restful-service.html


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章