Removing escape characters from a string (xml) and sending it to a WCF service
I'm trying to make a POST http request to my WCF Service and send ti some data in XML. I tried building an XML string both using XmlWriter and just string开发者_如何学运维 concatenation, but I always have escaping characters (\" and other) in my string, and so my POST fails.
This is how I build an XML String:
var data = string.Empty;
data += (@"<Root xmlns=""http://schemas.datacontract.org/2004/07/..."" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">");
data += (String.Format("<Element1>{0}</Element1>", element1));
data += (String.Format("<Element2>{0}</Element2>", element1));
data += (String.Format("<Element3>{0}</Element3>", element1));
data += (String.Format("<Element4>{0}</Element4>", element4));
data += (String.Format("</Root>"));
and I get \" characters in Root element because of xmlns attribute and its value. That's why my POST alaways returns 400 Bad Request. This is how I make a POST:
var req = WebRequest.Create(uri);
req.ContentType = "application/xml; charset=utf-8";
req.Method = "POST";
var bytes = Encoding.UTF8.GetBytes(data);
req.ContentLength = bytes.Length;
var os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Flush();
os.Close();
var response = _GetResponseString(req.GetResponse());
return response;
How to get rid of unwanted characters and make this POST working?
As you confirmed in the comments, the problem wasn't the escaped characters (it's usually a red herring that the watch window in VS shows them as if they were escaped), but something else.
Almost all the time where you have a problem where a WCF service is returning a 400 / 500 error to the client, enabling tracing should point you to the right direction in fixing the issue.
精彩评论