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

前端 未结 2 1415
-上瘾入骨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.

    0 讨论(0)
  • 2021-02-05 11:26

    What you are after is a custom MediaTypeFormatter. It sounds like you wish to implement your own custom one to replace and existing or you're creating a new custom one all together depending what what Accept header you're expecting. Good news is you can swap out existing ones or come up with a new MediaType of you like. A couple places that will help get you started can be found here:

    http://byterot.blogspot.com/2012/04/aspnet-web-api-series-part-5.html

    http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

    Yes, I've actually done this in small part as I've swapped out some of the default formatter e.g. JSON with a faster one i.e. ServiceStack and it works great.

    0 讨论(0)
提交回复
热议问题