We all know that by default WebAPI2 tends to add a backslash and quotes to the HttpResponseMessage
Content
message.
Using the standard action code:
public HttpResponseMessage Test()
{
return this.Request.CreateResponse(HttpStatusCode.OK, "Hello World");
}
Returns "\"Hello World\"" which displays "Hello World" (with the quotes).
Where if I change the API method and add encoding:
public HttpResponseMessage Test()
{
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Hello World", System.Text.Encoding.UTF8, "application/json")
};
and this solves the problem, as the Content
result becomes Hello World but just for the Test
method.
Great, but this has solved the problem only for the Test
method, not for all the other API methods.
Is there a simple and single way to add the UTF8 Encoding for all Controller
actions at once?
You don't seem understand what an encoding is. Find out because it is important to know. An encoding is a way to turn a string into bytes.
No encoding in the world adds a backslash and quotes. JSON adds them. JSON is a container format like XML is.
Don't use JSON if you don't want JSON. You don't need to specify UTF8 because it is the default. The default for string content. Write yourself a helper that created the HttpResponseMessage
any way you like. That way you can have any complicated logic you like and still construct a response in one line.
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