In WebAPI, say I return a string wrapped in an HTTP response:
return Request.CreateResponse(HttpStatusCode.BadRequest, "Line1 \r\n Line2");
When invoking this action from jQuery, the response text is treated before it is returned. So in the xhr, I get something like this:
function success(xhr) {
alert(xhr.responseText); // alerts ""Line1 \\r\\n Line2""
}
In other words, the string gets wrapped in double quotes, and special characters get escaped so that they appear in the output (actual alert is "Line1 \r\n Line2", so the newlines are not preserved, but rather encoded and shown in the response text).
I can get around this by removing the quotes and replacing the newlines on the client like so:
var responseText = xhr.responseText.substr(1, xhr.responseText - 2)
.replace('\\r', '\r').replace('\\n', '\n');
But is there a way to tell WebAPI how to format string responses? For example, not to wrap them in double quotes and convert escaped characters?