WCF 的 WebGet 方式

來源:互聯網
上載者:User

標籤:model   enabled   clu   false   知識庫   忘記   rac   response   3.5   

.NET 3.5以後,WCF中提供了WebGet的方式,允許通過url的形式進行Web 服務的訪問。在以前的代碼中,寫過多次類似的例子,但總是忘記如何配置,現在將設定步驟記錄如下:

  1. endpoint通訊通訊協定設定成  webHttpBinding
  2. endpoint的行為設定成 <webHttp />
  3. 在介面上加入 WebGet 的Attributes

範例程式碼如下: web.config檔案的配置

  <system.serviceModel>    <services>      <service name="Services.ShowerService">        <endpoint binding="webHttpBinding" behaviorConfiguration="WebBehavior" contract="Services.IShowerService" />      </service>    </services>    <behaviors>      <endpointBehaviors>        <behavior name="WebBehavior">          <webHttp />        </behavior>      </endpointBehaviors>      <serviceBehaviors>        <behavior name="">          <serviceMetadata httpGetEnabled="true" />          <serviceDebug includeExceptionDetailInFaults="false" />        </behavior>      </serviceBehaviors>    </behaviors>  </system.serviceModel>

  WCF介面的設定,這裡加入了對URI模板(UriTemplate)和JSON(WebMessageFormat.Json)的支援:

namespace Services{    [ServiceContract]    public interface ShowerService    {        [OperationContract]        [WebGet(UriTemplate="/Hello/{name}", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]        string Hello(string name);    }}

  測試:開啟IE瀏覽器,在地址欄輸入:http://localhost:3000/Services/ShowerService.svc/hello/abc,將會看到訪問後的結果。   調試:將Web.config中的 <webHttp /> 修改為 <webHttp helpEnabled="true" />將可以在瀏覽器頁面中列舉出可用介面,並提供提交的資料範例。開啟IE瀏覽器,在地址欄輸入:http://localhost:3000/Services/ShowerService.svc/help 即可。 Siverlight 訪問:使用SL的WebClient訪問WebInvoke方法時,不要忘記將 HttpRequestHeader.ContentType 設定成 application/json,代碼如下所示:

            WebClient client = new WebClient();            client.Headers[HttpRequestHeader.ContentType] = "application/json";

WCF 的 WebGet 方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.