2011-06-06 45 views
4

我正在使用WCF REST服務模板40(CS)。我扔WebFaultExceptions這樣:WCF 4.0 - 使用REST服務模板返回JSON WebFaultException

throw new WebFaultException<string>("Error Message", HttpStatusCode.BadRequest); 

然而,當我測試這跟我的客戶,一切都被返回的500 HTTP狀態碼,響應是XML。我可以在XML響應中看到錯誤消息。當我正確地打電話時,我收到了200響應,並且響應以JSON形式提供,根據我的配置和ServiceContract的設置方式,這是正確的。

我可以得到HTTP狀態代碼爲400的錯誤請求的唯一方法是做到這一點:

WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest; 

我仍然不能得到異常返回的JSON。

編輯添加簽名的詳細資料:

[OperationContract] 
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, UriTemplate = "myendpoint")] 

是否有一個簡單的方法來做到這一點?

+0

如果這是工作正常,狀態碼應該是400(壞請求)。您是否可以啓用跟蹤來查看是否有其他事情正在阻止WebFaultException 被處理?我剛剛使用REST服務模板創建了一個新項目,添加了(ResponseFormat = WebMessageFormat.Json)到其中一個操作,並添加了相同的行 - 並且響應編碼爲JSON而不是XML。 – carlosfigueira 2011-06-06 23:28:28

+0

難道是我在做我的代碼:catch(WebFaultException ex){throw; ''?如果需要,我還可以添加其他配置信息。 – Brandon 2011-06-07 02:29:12

+0

這應該不是問題;你能發佈操作契約的簽名([WebGet/WebInvoke]屬性)嗎? – carlosfigueira 2011-06-07 03:50:01

回答

4

在web.config中你設置AutomaticFormatSelectionEnabled的假

<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" /> 

設置響應格式爲JSON(你已經這樣做)的值

[WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)] 
4

WebHttpBehavior.FaultExceptionEnabled設置爲trueWebFaultException將導致200響應,儘管配置設置爲automaticFormatSelectionEnabled或響應格式屬性設置,但將錯誤呈現爲XML而非JSON。 MSDN文檔沒有提到這一點,誤導性是它聲明這個屬性只與500響應代碼有關。

+0

設置'WebHttpBehavior.FaultExceptionEnabled'爲'false'對我有幫助。否則,我總是會在每個拋出的「WebFaultException」上獲得500響應代碼。 – bertl 2015-03-06 10:44:00

0

對於那些仍然有這個問題。這對我工作

WebOperationContext.Current.OutgoingResponse.ContentType = "application/json"; 
throw new System.ServiceModel.Web.WebFaultException<Response>(
      new Response(false,"was not found", ""),System.Net.HttpStatusCode.BadRequest);