使 WCF Web 服務與 GET 請求一起工作
背景
我過去創建了 ASMX Web 服務,並且能夠從 Web 瀏覽器和使用地址約定的 Ajax GET 請求訪問該服務:
MyService.asmx/MyMethod?Param=xxx我剛開始使用 WCF,並在我的 ASP.NET 項目中創建了一個新的 Web 服務。它會創建一個副檔名為 .svc 的文件,例如 MyService.svc。
目前情況
我可以使用
WcfTestClientVS2008 附帶的服務來使用該服務。我還可以通過在另一個項目中添加服務引用或使用svcutil.exe命令行生成代理和配置文件來創建自己的 WCF 客戶端。問題
當我嘗試使用瀏覽器使用該服務時
MyService.svc/MyMethod?MyParam=xxx,我得到一個沒有任何錯誤的空白頁面。我已經嘗試過
,我已經在 web.config 中添加了一個basicHttpBinding ,並在行為配置中將其設為 HttpGetEnabled。我還將該
[WebGet(UriTemplate = "MyMethod?MyParam={MyParam}")]屬性添加到我的操作合同中。我已經關注了另一個堆棧溢出問題中的資訊:
REST / SOAP EndPoints for a WCF Service
但是,執行這些步驟後,我要麼得到一個空白頁,要麼得到一個 HTTP 404 錯誤。程式碼沒有什麼特別之處。我只是將一個字元串作為參數並返回“Hello xxx”。這是一個基本的“Hello WCF World”概念驗證類型的東西。
更新- 這是相關程式碼
[ServiceContract] public interface IMyService { [WebGet(UriTemplate = "MyMethod/MyParam={MyParam}")] [OperationContract] string MyMethod(string MyParam); }Web.Config - system.serviceModel 部分
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="MyServiceBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="MyServiceBehavior" name="MyService"> <endpoint address="" binding="wsHttpBinding" contract="IMyService" /> <endpoint address="MyService.svc" binding="basicHttpBinding" contract="IMyService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> </system.serviceModel>
查看您的
web.configserviceModel 部分,我可以看到您需要添加一個webHttpBinding並關聯一個包含webHttpGet 的endPointBehavior。您的操作合同是正確的。這是您的 system.serviceModel 配置部分的外觀,以便您能夠從 GET HTTP 請求中使用服務。
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="MyServiceBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="WebBehavior"> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <services> <service behaviorConfiguration="MyServiceBehavior" name="MyService"> <endpoint address="ws" binding="wsHttpBinding" contract="IMyService"/> <endpoint address="" behaviorConfiguration="WebBehavior" binding="webHttpBinding" contract="IMyService"> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> </system.serviceModel>請務必為您的 wsHttpBinding 端點分配不同的地址,否則您將收到錯誤消息,指出您有兩個端點正在偵聽同一個 URI。
另一種選擇是將 wsHttpBinding 中的地址留空,但為 webHttpBinding 服務分配不同的地址。但是,這也會改變您的 GET 地址。
例如,如果您將地址分配為“asmx”,您將使用地址“
MyService.svc/asmx/MyMethod?MyParam=xxxx”呼叫您的服務。