转义从我的API方法传入的转义字符

时间:2014-05-13 19:58:56

标签: c# xml api asp.net-web-api

生成我的xml的我的API方法看起来像这样(很好)

"<?xml version=\"1.0\" encoding=\"UTF-8\"?>

但介于我的api方法之间

 return Request.CreateResponse(HttpStatusCode.OK, res);

我从

获取回复的地方
string api_response = client.UploadString(myurl, myRequest)

我上面的api_response字符串如下所示

"\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>

导致我的XDocument.Parse失败

编辑:更多细节 我正在通过此代码获得响应

  HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
            httpRequest.Method = "POST";
            httpRequest.ContentType = "text/xml; charset=utf-8";
            httpRequest.Accept = "text/xml";
            httpRequest.Credentials = new NetworkCredential(userName, password);
            byte[] bytesToWrite = Encoding.UTF8.GetBytes(root.ToString());

            using (Stream st = httpRequest.GetRequestStream())
            {
                st.Write(bytesToWrite, 0, bytesToWrite.Length);
            }

            HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
            string read = reader.ReadToEnd();
            return read;

读取返回格式良好的xml: 只有在我的CreateResponse之后才会出现额外的反斜杠(看着点击放大玻璃选项的字符串)

当我从我的api返回响应时(作为Internet Explorer上的文本),我的实际文本是这样的“

想出来 用ResponseMessage替换我的

var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted) {
      RequestMessage = Request,
      Content = new StringContent(content)
    };
    return ResponseMessage(httpResponseMessage);

1 个答案:

答案 0 :(得分:3)

好的改变了

 return Request.CreateResponse(HttpStatusCode.OK, res);

var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted) {
      RequestMessage = Request,
      Content = new StringContent(content)
    };
    return ResponseMessage(httpResponseMessage);