利用WCF建立簡單的RESTFul Service

Eric Sun發表於2015-01-26

1):用VS2013建立一個WCF的工程,如下圖所示:

 

2):我們來看一下預設狀態下的config檔案內容,這裡的內容我們會再後續的步驟中進行修改

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

 

3):我們對工程檔案及其內容做一下修改,具體程式碼如下所示:

3.1):UserData class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;

namespace EricSunWcfService
{
    [DataContract]
    public class UserData
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Password { get; set; }
        [DataMember]
        public string Email { get; set; }
    }
}

 

3.2):IDataService,這個介面是從預設的IService1修改而來,並且這裡提供了兩種方法,一個是GET,另外是POST,都是簡單的返回UserData物件的Json字串

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace EricSunWcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IUserService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "getuser/{name}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        UserData GetUserData(string name);

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "checkuser", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        UserData CheckUserData(UserData user);
    }
}

 

3.3):UserService,這個檔名是從預設的Service1修改過來的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace EricSunWcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class UserService : IUserService
    {
        public UserData GetUserData(string name)
        {
            UserData user = new UserData();
            user.Name = name;
            user.Email = "test@123.com";
            return user;
        }

        public UserData CheckUserData(UserData user)
        {
            user.Name += "-test";
            return user;
        }
    }
}

 

3.4):我們可以點選對應的Service的‘View Markup’來修改ServiceHost的資訊,如下圖所示

 

4):我們在IIS中建立一個Site來Host我們所提供的WCF Service,用http協議並且將埠繫結為8089,與此同時制定好Physical path,如下圖所示

【注:請將建立的Application Pool的.Net Framework Version修改成為4.0】

 

5):在目前這種狀態下還不能成功的訪問對應的WCF Service的,我們需要對web.config進行修改

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <services>
        <service name="EricSunWcfService.UserService" behaviorConfiguration="RESTBehaviour">
          <endpoint address=""
                    binding="webHttpBinding"
                    contract="EricSunWcfService.IUserService"
                    behaviorConfiguration="ESEndPointBehavior"/>
        </service>
      </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="RESTBehaviour">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
        
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ESEndPointBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <!--
      To browse web app root directory during debugging, set the value below to true.
      Set to false before deployment to avoid disclosing web app folder information.
    -->
    <directoryBrowse enabled="true"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

 

6):config檔案配置完畢後,我們就可訪問此URL:http://localhost:8089/UserService.svc 來判斷我們Service提供的正確與否,若是看到下面的截圖則表明Service無誤

 

7):若在訪問 http://localhost:8089/UserService.svc 的時候出現500.19【HTTP Error 500.19 - Internal Server Error】錯誤請參考如下連結解決

http://www.cnblogs.com/mingmingruyuedlut/archive/2011/11/04/2235630.html 

 

8):訪問GET方法我們可以直接在瀏覽器位址列中輸入對應的service地址即可訪問

例如輸入 http://localhost:8089/UserService.svc/getuser/eric

會給我們返回: {"Email":"test@123.com","Name":"eric","Password":null}

 

9):若是訪問POST方法,單純的在瀏覽器中輸入地址則無法完成正確的呼叫,這裡我們使用瀏覽器的外掛poster (https://addons.mozilla.org/en-US/firefox/addon/poster/)

 

如上圖所示,在poster中填入正確的配置資訊,並且傳入Json的引數值{"Email":"test@123.com","Name":"eric","Password":"123"}

點選POST按鈕之後變回得到如下返回結果:

 

10):若是我們發現在呼叫PUT或者DELETE方法時出現Status:405 Method Not Allowed的問題,請在web.config檔案中的system.webServer節點中新增如下配置

    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <remove name="WebDAV" />
    </handlers>

 

至此我們就可以通過WCF向外提供REST的Service了~~

如何配置來完成HTTPS的訪問請看如下連結:

http://www.cnblogs.com/mingmingruyuedlut/p/4236035.html

 

相關文章