如何防止ReadAsStringAsync返回双重转义的字符串?

Gro*_*ile 18 c# asp.net-web-api

我有一个Web API方法,看起来有点像这样:

    [HttpPost]
    public ResponseMessageResult Post(Thing thing)
    {
        var content = "\r";
        var httpResponseMessage = Request.CreateResponse(HttpStatusCode.Accepted, content);
        return ResponseMessage(httpResponseMessage);
    }
Run Code Online (Sandbox Code Playgroud)

在其他一些客户端代码中,当我打电话时:

    var content = httpResponseMessage.Content.ReadAsStringAsync().Result;
Run Code Online (Sandbox Code Playgroud)

content 是:

    "\\r"
Run Code Online (Sandbox Code Playgroud)

但我希望它保持原状:

    "\r"
Run Code Online (Sandbox Code Playgroud)

为什么客户端收到双重转义的字符串,如何防止它发生?

Jos*_*osh 39

我知道通过这样做我可能会导致70亿条代码执行(对不起Darrel Miller)但我发现它对我选择的开发模式使用它同样有效,并且破坏性更小:

response.Content.ReadAsAsync<string>().Result;
Run Code Online (Sandbox Code Playgroud)

要么

await response.Content.ReadAsAsync<string>();
Run Code Online (Sandbox Code Playgroud)

而不是这个(逃脱报价):

response.Content.ReadAsStringAsync().Result;
Run Code Online (Sandbox Code Playgroud)

注意:ReadAsAsync在一个扩展方法System.Net.Http.HttpContentExtensions,在System.Net.Http.Formatting组装.如果它在您的项目中不可用,您可以添加NuGet包Microsoft.AspNet.WebApi.Client.

  • 这个答案对我来说效果更好.提到的扩展方法可以在Microsoft.AspNet.WebApi.Client.dll中找到,因为默认情况下它不是web api模板的一部分 (2认同)

Dar*_*ler 23

它正在做它正在做的事情因为你用大锤开裂了一个鸡蛋.

当您打电话时,Request.CreateResponse<string>(HttpStatusCode statusCode, T value)您正在告诉Web API您希望使用其中一种媒体类型格式化程序序列化您的值.因此,Web API value会将您填充到ObjectContent的实例中,执行大量的连接代码,并确定它可以使用Formatter X来序列化您的"对象".

有可能是JSONSerializer正在尽力尝试返回它认为你想要的字符串而不是CR字符.

无论如何,你可以通过使用HttpContent对象来切换到追逐并避免执行70 bajillion代码行,该对象旨在通过线路发送简单的字符串.

[HttpPost]
public ResponseMessageResult Post(Thing thing)
{
    var content = "\r";
    var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted) {
      RequestMessage = Request,
      Content = new StringContent(content)
    };
    return ResponseMessage(httpResponseMessage);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,你大大改善了我的一天! (2认同)