How to set the default RequestFormat for a WCF ServiceContract?
Asked Answered
M

2

8

I'm writing a web service that has a lot of methods. They are all set up similar to the following:

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

What I want to do is just set the default BodyStyle / RequestFormat / ResponseFormat all in the web.config file. Now, I know I can do this:

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

But there doesn't seem to be an attribute for the RequestFormat. How can I set the default RequestFormat to JSON?

Maliamalice answered 2/8, 2012 at 21:46 Comment(0)
C
5

Request types are automatically interpreted by WCF, you don't need to specify a default RequestFormat for your service operation.

If you are trying to enforce the supported request format, see this related SO post on enforcing request content types.

Note: it doesn't make sense to assign a RequestFormat for a WebGet operation. By definition, a WebGet cannot contain a Body which is where the JSON format would exist. A better example here would be WebInvoke.

Condyle answered 3/8, 2012 at 13:19 Comment(2)
Thanks for the clarification! So as long as the body specifies "application/json" format, WCF will automatically pick it up, correct?Maliamalice
An interesting tidbit I found from your link: "If no default format is specified on the operation, the value of the DefaultOutgoingResponseFormat property is used." So basically, if the poster doesn't specify the content type, and there's no RequestFormat on the operation, it will actually pick up the format from the defaultOutgoingResponseFormat. Interesting.Maliamalice
A
1

Set the automaticFormatSelectionEnabled property to true in webHttp element in web.config file

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


eg: you can set Accept:application/json in recieving end and get JSON result.

postman screens

Json response

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

Xml response


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

Adessive answered 17/7, 2015 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.