Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI ensuring all Responses are automatically UTF8 encoded to avoid unwanted Backlash & Quotes

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?

like image 360
SF Developer Avatar asked Aug 08 '14 17:08

SF Developer


1 Answers

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.

like image 111
usr Avatar answered Nov 05 '22 06:11

usr