標籤:model enabled clu false 知識庫 忘記 rac response 3.5
.NET 3.5以後,WCF中提供了WebGet的方式,允許通過url的形式進行Web 服務的訪問。在以前的代碼中,寫過多次類似的例子,但總是忘記如何配置,現在將設定步驟記錄如下:
- endpoint通訊通訊協定設定成 webHttpBinding
- endpoint的行為設定成 <webHttp />
- 在介面上加入 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 方式