we have JSON configuration data stored in a database. i need to fetch this JSON data and return it, as it is, to the browser via asp.net web-api:
public class ConfigurationController : ApiController
{
public string Get(string configId)
{
// Get json from database
// when i return the fetched json it get's escaped
}
}
The value that i return gets escaped. how do i simply return the string as it is? I really don't want to populate an object that gets serialized to JSON.
JSON is pretty liberal: The only characters you must escape are \ , " , and control codes (anything less than U+0020).
Escapes or unescapes a JSON string removing traces of offending characters that could prevent parsing. The following characters are reserved in JSON and must be properly escaped to be used in strings: Backspace is replaced with \b. Form feed is replaced with \f.
By default, Web API produces XML but if there is need for JSON, given syntax will do it. Open WebApiConfig. cs file in solution and add mentioned line in it as shown in example.
You can return a HttpResponseMessage
from the ApiController which allows you to basically return a string value.
e.g.
public HttpResponseMessage Get()
{
return new HttpResponseMessage() {
Content = new StringContent("Hello World", System.Text.Encoding.UTF8, "application/json")
};
}
What you would want to do is just pass the json string as the StringContent.
The accepted answer is slightly off. The correct version is:
public HttpResponseMessage Get()
{
return new HttpResponseMessage() {
Content = new StringContent("Hello World", System.Text.Encoding.UTF8, "application/json")
};
}
It's the StringContent function that correctly removes the escaping. Without the application/json media type, tools like postman won't correctly display the "pretty" version of the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With