How does WCF decide when SOAP or JSON is returned depending on the request?

I just created my first WCF REST service. I wanted it to return JSON, so I highlighted the response format. At first I was upset because he was returning SOAP all the time, and I did not know why, but I saw that the blogger was using Fiddler, so I tried with it and then received a JSON response.

I think the reason is that Fiddler does not send this HTTP header:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 

But then I tried to process the request using this header:

 Accept: application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 

But that did not work. How does WCF decide when to use JSON or SOAP?

Is there a way to force JSON back?

I would like to be sure that when I use the service, it will return JSON, not SOAP.

Thanks.

Update : Code example:

 [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class Service1 { [WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json, RequestFormat= WebMessageFormat.Json)] public List<SampleItem> GetCollection() { // TODO: Replace the current implementation to return a collection of SampleItem instances return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } }; } [WebInvoke(UriTemplate = "", Method = "POST")] public SampleItem Create(SampleItem instance) { // TODO: Add the new instance of SampleItem to the collection throw new NotImplementedException(); } [WebGet(UriTemplate = "{id}", ResponseFormat = WebMessageFormat.Json)] public SampleItem Get(string id) { // TODO: Return the instance of SampleItem with the given id return new SampleItem() { Id = Int32.Parse(id), StringValue = "Hello" }; } } 
+1
source share
3 answers

I have a finite behavior like this

 <endpointBehaviors> <behavior name="jsonEndpoint"> <webHttp defaultOutgoingResponseFormat="Json" /> </behavior> </endpointBehaviors> 

If you configure this as endpoint behavior, you do not need to touch work contracts, and they can create different outputs if they are accessed through another endpoint.

The only thing I'm not quite sure about is the two different Json styles that WCF seems to be creating. If you use enableWebScript, this will create the format "{d": {...}} Json, and the defaultOutgoingResponseFormat option set to Json will not be a d-object, but just Json.

+2
source

I need to take a look at your code to understand what exactly you are doing. But check quickly here. Have you applied the following attributes to your service definition?

[System.ServiceModel.Web.WebGet(ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]

+1
source

Have you tried configuring your service to use webHttpBinding?

Print webHttpBinding endpoint in WCF service

0
source

Source: https://habr.com/ru/post/1403667/


All Articles