WCF服務的Web HTTP方式


NET 3.5以后,WCF中提供了WebGet的方式,允許通過url的形式進行Web 服務的訪問。現將WCF服務設置步驟記錄如下:

  1. endpoint通訊協議設置成  webHttpBinding

  2. endpoint的行為設置成 <webHttp />

  3. 在接口上加入 WebGet 的Attributes

示例代碼如下: web.config文件的配置 

 <system.serviceModel>
    <services>
      <service name="Services.ShowerService">
         /*提供Web HTTP服務用*/
        <endpoint binding="webHttpBinding" behaviorConfiguration="WebBehavior" contract="Services.IShowerService" />
      </service>
    </services>
    <behaviors>
      <!--WCF中提供了Web HTTP的方式-->
      <endpointBehaviors>
        <behavior name="WebBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <!--WCF中提供了Web HTTP的方式-->

      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="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";

 


免責聲明!

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



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