Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default RequestFormat for a WCF ServiceContract?

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?

like image 323
Ryan J. Thompson Avatar asked Aug 02 '12 21:08

Ryan J. Thompson


2 Answers

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.

like image 149
SliverNinja - MSFT Avatar answered Nov 15 '22 12:11

SliverNinja - MSFT


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

like image 44
Sameera R. Avatar answered Nov 15 '22 13:11

Sameera R.