The WCF Service is experiencing issues when attempting to call a client for accessing REST with JSON, as the correct content type is

I've been struggling with a perplexing issue for the past few days - I'm trying to utilize a WCF service to call another RESTful service.

However, as I trace through the process, it consistently fails to set the appropriate JSON content type on the message.

Below is an example of the call in the client code (within a WCF service that makes the call):

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior()]
public partial class MyRestServiceClient : System.ServiceModel.ClientBase<IMyRestService>, IMyRestService
{
    [WebInvoke(Method = "POST", UriTemplate = "/MyService/ReferenceTypes.json", RequestFormat = WebMessageFormat.Json)]
    public MyServiceLists GetReferenceTypes()
    {
        try
        {
            return base.Channel.GetReferenceTypes();
        }
        catch (Exception e)
        {
            throw e; //throws exception here - method not allowed 
        }
    }
}

The issue lies in the fact that instead of setting the content type to application/json, it mistakenly sets it to application/xml. This was deduced from activity tracing data logged by the WCF service responsible for initiating the call.

For instance, here's a snippet of the "message sent" information from the Activity log:

<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
...
**<Encoder>application/xml; charset=utf-8</Encoder>**
...

I've attempted using a `webHttpBinding` and even tried a custom binding with a custom web content type mapper specifically designed to enforce a JSON content type, but to no avail.

The client endpoint is directed towards a RESTful service (utilizing the Rest 40 template) on the same machine. Below is the relevant excerpt from the `web.config` file of the WCF service:

<?xml version="1.0"?>
<configuration>
...

It's worth noting that a console application I developed with similar functionality and configuration does work correctly and sets the correct content type.

Any assistance or guidance you can offer would be greatly appreciated.

Answer №1

If you haven't resolved this yet, I encountered the same problem before.
To fix it, you have to enclose the new service call within a new OperationContextScope.

Check out more details here: WCF Rest Client sending incorrect content-type

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Processing JSON Serialization from Controller to AJAX Response

I'm struggling to find the correct way to use an HttpWebRequest, and then convert its response into a readable format of JSON for a JavaScript AJAX function. If I just return the raw text, it includes escaping slashes in the response. If I deserializ ...

Transforming a string field into a property object through deserialization

Assuming I have a serialized Json object of type MyClass like this: {"DurationField":"3 Months", *OtherProperties*} My goal is to deserialize this Json into the following class structure: public class MyClass{ *OTHER PROPERTIES* p ...

Breaking down this JSON (array)

Greetings! I have a section of JSON data that requires parsing, and I have condensed it for better visibility. [ { "trends": [ { "name": "#CyberMonday", "url": "https://twitter.com" }, { "name": "#Bl ...

Create a new JSON array by filtering this JSON array based on a specific date range

Having a json array that contains the following keys and values: { "results": [ { "date": "2013-15-5", "position": "23", "race" : "2" }, { "date": "2013-15-6", "positio ...

Map dynamic values and headers in Jolt JSON Transformation Specification

Looking for guidance on converting the input JSON to output JSON while ensuring that field values are compared accurately in a JOLT transformation. Input: { "response": { "body": { "variables": { "swa ...

Utilize a for loop in Vue.js to save a fresh array of objects in a structured format

Trying to achieve the following using Vue: I have two JSON objects that provide information on languages and the number of inputs per language. Using nested loops, I display all the inputs. My goal is to create an object for each input with additional det ...

For every item in the loop, iterate through it using PHP and

Hey there! I need some help with PHP and JSON. I'm currently running this PHP code in a foreach loop, but when I try to extract all the tank IDs from the JSON file, they appear like this: 8011819314145 What I actually want is for them to display a ...

Creating a custom output using PHP, MySQL, and JSON

When I retrieve and print data from a MySQL database using the json method, it looks like this: $ret = array(); $fileName = Access::FetchDB("SELECT name FROM tags"); $ret[] = $fileName; echo json_encode($ret); The current output is: [[{"name":"test1"},{ ...

javascript retrieving JSON data through an API request from a redirected URL

I am retrieving JSON data from the Glitch API. Upon opening the link, it redirects to a different domain (the domain was changed from gomix.me to glitch.me) When using Postman for both HTTP requests, I receive identical JSON data. However, there is a d ...

Perform an HTTP/1.1 GET call on an Android device

I'm currently in the process of making a request to an API. The API has certain requirements that must be adhered to: The Base URL for our API can be found at (make sure to note the version number 1 after the /) All requests to the API should be ma ...

Ways to categorize JSON information

Is it possible to group JSON data by group_name? JSON : [ {"fullname":"fffffffff","email":"sss@gg","mobile":"3333333333","designation":"ggg","group_name":"engineers"}, {"fullname":"ddddddddddd","email":"sssg@gg","mobile":"3333333333","designation":"ffff ...

Rendering Information in Angular 4 Through Rest API

Encountering issues displaying data from my local express.js REST API, organized as follows: people: [{ surname: 'testsurname', name: 'testname', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

What does the term "false = %x66.61.6c.73.65 ; false" mean according to JSON RFC 4627?

Currently, I am going through RFC 4627 (http://www.ietf.org/rfc/rfc4627.txt). Section 2.1 discusses the three literal names: true, false, null. false = %x66.61.6c.73.65 ; false null = %x6e.75.6c.6c ; null true = %x74.72.75.65 ...

How can I send a JSON POST request using Delphi's TIdHttp

Has anyone had success using JSON with TIdHttp? I am having an issue where the PHP code always returns NULL in the $_POST, is there something I'm missing or doing wrong? Here's the Delphi source: http := TIdHttp.Create(nil); http.HandleRedirec ...

pydantic.error_wrappers.ValidationError: There is 1 validation error for object B

Every time I attempt to parse a JSON object using Pydantic, my IDE keeps throwing an error... Here's the code snippet causing the issue: from pydantic import BaseModel, Field class A(BaseModel): a: str = Field(None, alias="А") class ...

Using the FileInput Shiny App to Upload JSON Files

I'm currently working on developing a shiny app that can load and display data from a .json file in a table format. I've attempted to import the data and present it using DataTable along with the fromJson function from Json Lite. options(shiny ...

Interconnected Dropdown Menus

I've implemented the cascading dropdown jQuery plugin available at https://github.com/dnasir/jquery-cascading-dropdown. In my setup, I have two dropdowns named 'Client' and 'Site'. The goal is to dynamically reduce the list of si ...

Is there a clash between Angular JS $scope and the MIME content-type in an API's HTTP response?

While experimenting with an AngularJs app, I am consuming a REST API using Slim PHP through $http (and planning to use $resource next). The data retrieval from the API works perfectly when the controller is set up like this: angular .module("adminTall ...

Encountering a null pointer exception when using a post method, JSON, and AJAX

Implementing Server Side Logic @Path("/create") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}) public RequestStatus createData(String jsonData){ return ...

Loop through a JSON object and save references in a Swift program

Upon receiving a JSON payload from a web request, the task at hand involves extracting the data and assigning it to variables within an NSObject subclass. The object contains the following variable declarations: var name:String? var email:String? var abo ...