.netescapinghttpclientresponse

HttpResponseMessage text/plain content is being wrapped in quotes and escaped


I have created a webapi that returns a TOML config file, when I look at the output in swagger/postman the output is as I expect:

[systems."test 2"]
name = "testname"
organisation = "testorg"

But when I read the response from HttpClient.GetAsync with respose.Content.ReadAsStringAsync() the data is wrapped in quotes and the contents is escaped:

"[systems.\"test 2\"]\r\nname = \"testname\"\r\norganisation = \"testorg\""

I've tried the read as stream with the stream reader and I get the same escaped version. How do i get the raw string and why is this happening? I know I can use Regex.Unescape to get rid of the escaping but then there are still the surrounding quote marks. Which I know I can just remove but it all seems a bit strange, I would like to know why this is happening

For reference in the WebAPI I am just returning an IActionResult of Ok(string)


Solution

  • The problem was my HttpClient had default headers of accept application/json and so it seems it attempted to parse it as json thus causing an extra layer of escaping.

    I have fixed this by changing creating a HttpRequestMessage and setting the Accept header to text/plain