2012-08-02 22 views
8

我在寫一個有很多方法的web服務。他們都成立了類似以下內容:如何爲WCF ServiceContract設置默認的RequestFormat?

[OperationContract] 
    [WebInvoke(
     BodyStyle = WebMessageBodyStyle.Bare, 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     UriTemplate = "x/y/z")] 
    void someMethod(int x, int y, int z); 

我想要做的就是設置默認BodyStyle/RequestFormat/ResponseFormat所有在web.config文件中。現在,我知道我可以這樣做:

<endpointBehaviors> 
    <behavior name="webHttpBehavior"> 
     <webHttp defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Json" /> 
    </behavior> 
    </endpointBehaviors> 

但是似乎並沒有RequestFormat的屬性。我如何將默認RequestFormat設置爲JSON?

回答

5

請求類型爲automatically interpreted by WCF,您無需爲您的服務操作指定默認的RequestFormat

如果您試圖執行支持的請求格式,請參閱this related SO post on enforcing request content types

備註:RequestFormat指定爲WebGet操作沒有任何意義。根據定義,WebGet不能包含JSON格式存在的Body。一個更好的例子是WebInvoke

+1

謝謝澄清!所以只要body指定「application/json」格式,WCF就會自動提取它,正確嗎? – 2012-08-03 15:56:51

+3

我從鏈接中找到一個有趣的小技巧:「如果在操作中沒有指定默認格式,則使用DefaultOutgoingResponseFormat屬性的值。」所以基本上,如果海報沒有指定內容類型,並且操作上沒有RequestFormat,它實際上會從defaultOutgoingResponseFormat中選取格式。有趣。 – 2012-08-03 16:02:44

1

元素設置automaticFormatSelectionEnabled屬性truewebHttp在web.config文件

<behaviors> 
    <endpointBehaviors> 
     <behavior> 
     <webHttp automaticFormatSelectionEnabled="true" /> 
     </behavior> 
    </endpointBehaviors> 
</behaviors> 


例如:你可以在recieving年底成立Accept:application/json並獲得JSON結果。

郵遞員屏幕

Json response

================================== ==================================

Xml response


https://msdn.microsoft.com/en-us/library/ee476510(v=vs.110).aspx