1

I have two applications. A requesting client application written in ASP.NET Core 2 (we can call the "client"), and a responding/API application written in ASP.NET 4 Web API (we can call the "server"). The former is making a request to the latter, and I'm looking to receive, and subsequently parse, XML from the web API application.

The client is making an HTTP request using the following setup:

HttpClient httpClient = new HttpClient()
{
    BaseAddress = new Uri(communicatorUri)
};
httpClient.DefaultRequestHeaders.Add("Accept", "application/xml");

HttpResponseMessage responseMessage = await this.HttpClient.PutAsync(
    "api/customer",
    new StringContent(customerDetails.ToString(), Encoding.UTF8, "application/json")
);

It's sending through JSON, and expecting an XML response. The server is processing the JSON, and hopefully returning an XML response:

string response = "<note>Well formed XML string</note>";
return Ok(response);

Where this response arrives back at the client:

string responseString = await responseMessage.Content.ReadAsStringAsync();
XDocument xml = XDocument.Parse(responseString);

However, every time the response arrives back, it appears as if it's been double-encoded with \"'s. For example, it may look like "\"<note attr=\\\"test\\\">Well formed XML string</note>", and so subsequently it is obviously no longer valid XML, so parsing fails via a thrown exception.

Where do I start to actually fix this? I'm a bit confused as to whether I need to make changes with my requester, or my response, or even both.

1 Answer 1

2

Update the controller on the server:

public HttpResponseMessage Get()
{
  //process the request 
  .........

  string XML="<note><body>Message content</body></note>";
  return new HttpResponseMessage() 
  { 
    Content = new StringContent(XML, Encoding.UTF8, "application/xml") 
  };
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yup, this is correct. I did try this, but I was still returning an IHttpActionResult by wrapping the above HttpResponseMessage in Ok(), which is not a great idea. Using HttpResponseMessage directly like this is the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.