2012-08-02 12 views
8

Sto scrivendo un servizio web che ha molti metodi. Sono tutti impostati simile al seguente:Come impostare il RequestFormat predefinito per un ServiceContract WCF?

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

Quello che voglio fare è semplicemente impostare il valore predefinito BodyStyle/RequestFormat/ResponseFormat tutto nel file web.config. Ora, so che posso fare questo:

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

Ma non sembra essere un attributo per il RequestFormat. Come posso impostare il valore predefinito da RequestFormat a JSON?

risposta

5

I tipi di richiesta sono automatically interpreted by WCF, non è necessario specificare un valore predefinito RequestFormat per l'operazione di servizio.

Se si sta tentando di applicare il formato della richiesta supportata, vedere this related SO post on enforcing request content types.

Nota: non è opportuno assegnare un RequestFormat per un'operazione WebGet. Per definizione, un WebGet non può contenere un Body, che è dove il formato JSON esisterebbe. Un esempio migliore qui sarebbe WebInvoke.

+1

Grazie per il chiarimento! Quindi, finché il corpo specifica il formato "application/json", WCF lo rileverà automaticamente, corretto? –

+3

Una curiosità interessante che ho trovato dal tuo link: "Se non viene specificato alcun formato predefinito sull'operazione, viene utilizzato il valore della proprietà DefaultOutgoingResponseFormat." Quindi, in sostanza, se il poster non specifica il tipo di contenuto e non c'è alcun RequestFormat sull'operazione, in realtà prenderà il formato da defaultOutgoingResponseFormat. Interessante. –

1

Impostare la proprietà automaticFormatSelectionEnabled a true in webHttp elemento del file web.config

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


ad esempio: è possibile impostare Accept:application/json in recieving finale e ottenere il risultato JSON.

schermi postino

Json response

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

Xml response


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

Problemi correlati