ASP.NET WebAPI: How to control string content returned to client?

前端 未结 2 1446
-上瘾入骨i
-上瘾入骨i 2021-02-05 11:08

In WebAPI, say I return a string wrapped in an HTTP response:

return Request.CreateResponse(HttpStatusCode.BadRequest, \"Line1 \\r\\n Line2\");

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 11:15

    This happens because your controller is returning JSON in which string values are quoted.

    A simple solution is to parse the responseText as JSON and then you can use the value as intended:

    $.ajax("/api/values/10", {
        error: function (xhr) {
            var error = JSON.parse(xhr.responseText);
            $("textarea").val(error);
        }
    });
    

    This correctly interprets the line breaks/carriage returns.

    Alternatively you can specify the text/plain media type in your controller:

    return Request.CreateResponse(
        HttpStatusCode.BadRequest, 
        "Line1 \r\n Line2", "text/plain");
    

    Web API will then try and load an appropriate media type formatter for text/plain which unfortunately does not exist OOTB. You'll find one in WebApiContrib.

提交回复
热议问题