2012-08-02 26 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