如何防止ReadAsStringAsync返回一个双转义字符串? [英] How do I prevent ReadAsStringAsync returning a doubly escaped string?

查看:2707
本文介绍了如何防止ReadAsStringAsync返回一个双转义字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  [HttpPost] 
公共ResponseMessageResult帖子(事嘛)
{
VAR内容=\r;
VAR httpResponseMessage = Request.CreateResponse(HttpStatusCode.Accepted,内容);
返回ResponseMessage(httpResponseMessage);
}

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

  VAR内容= httpResponseMessage.Content.ReadAsStringAsync()结果。 



内容是:



 \\r

但我想它继续担任原来的:

 \r

为什么客户端接收双重转义字符串,我怎么能阻止它发生呢?


< DIV CLASS =h2_lin>解决方案

这是做什么就做,因为你是杀鸡用大锤一个鸡蛋。



在叫 Request.CreateResponse<串GT;(HttpStatusCode的StatusCode,T值)你是在告诉网络API,你想使用的介质类型格式化的一个序列化你的价值。因此,网页API充塞你的进入ObjectContent的一个实例做的conneg代码整体转换,并确定它可以使用格式化x可序列化的对象。



可能的是这是尽最大努力尝试的回报,你认为你想,而不是CR字符的字符串JSONSerializer。



反正你可以切入正题,避免通过使用专为通过电线发送简单的字符串HttpContent对象执行的代码70 bajillion行。

  [HttpPost] 
公共ResponseMessageResult邮报(事嘛)
{
VAR内容=\r;
变种httpResponseMessage =新HttpResponseMessage(HttpStatusCode.Accepted){
RequestMessage =请求,
含量=新的StringContent(内容)
};
返回ResponseMessage(httpResponseMessage);
}


I have a Web API method that looks a bit like this:

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

In some other client code, when I call:

    var content = httpResponseMessage.Content.ReadAsStringAsync().Result;

content is:

    "\\r"

but I would like it to remain as the original:

    "\r"

why is the client receiving a doubly escaped string and how can I prevent it happening?

解决方案

It is doing what it is doing because you are cracking an egg with a sledgehammer.

When you call Request.CreateResponse<string>(HttpStatusCode statusCode, T value) you are telling web API that you would like your value serialized using one of the media type formatters. So Web API stuffs your value into an instance of ObjectContent does a whole slew of conneg code, and determines that it can use Formatter X to serialize your "object".

Chances are it is the JSONSerializer that is doing its best to try an return you the string it thinks you want rather than the CR character.

Anyway you can cut to the chase and avoid executing 70 bajillion lines of code by using the HttpContent object that is designed for sending simple strings over the wire.

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

这篇关于如何防止ReadAsStringAsync返回一个双转义字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆