利用WCF建立簡單的RESTFul Service

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

 

2):咱們來看一下默認狀態下的config文件內容,這裏的內容咱們會再後續的步驟中進行修改web

<?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 classapp

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字符串post

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修改過來的this

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的信息,以下圖所示spa

 

4):咱們在IIS中建立一個Site來Host咱們所提供的WCF Service,用http協議而且將端口綁定爲8089,與此同時制定好Physical path,以下圖所示firefox

【注:請將建立的Application Pool的.Net Framework Version修改爲爲4.0】插件

 

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

<?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

相關文章
相關標籤/搜索