1

I'm working on an ASP.NET MVC application. There's a service which I need to send RESTful requests to. In this particular case, I have to use a POST to send XML to the service. We are not using WCF.

The XML is in an XElement object. The original XML includes character encoding information. I want to keep the character encoding unchanged when I write the XML to the service.

I can get a reference to the request stream using code like this:

HttpWebRequest req = (HttpWebRequest) WebRequest.Create( url );
req.Method = "POST";
req.Timeout = 30000;
Stream requestStream = req.GetRequestStream();

I've written this code:

using ( XmlWriter writer = new XmlTextWriter( requestStream, Encoding.UTF8 ) ) {
    xml.WriteTo( writer );
}

But this may change the encoding of the XML. It's important that the encoding doesn't change. I can't seem to find a property or method that returns the encoding of the XElement.

How do I write the XElement to the requestStream and preserve the existing character encoding?

Tony Vitabile
  • 8,298
  • 15
  • 67
  • 123
  • Could you give us more information? Are you trying to write the XML directly into the HttpResponse? – Fals Aug 01 '13 at 19:17
  • No, I'm trying to write the XML directly to the `HttpWebRequest`. The second sentence in my first paragraph says what I'm trying to do: "In this particular case, I have to USE a POST to send XML to the service." – Tony Vitabile Aug 01 '13 at 19:21
  • You should take a look here. You must specify the encode into the request. http://stackoverflow.com/questions/543319/how-to-return-xml-in-asp-net – Fals Aug 01 '13 at 19:33
  • @Fals: thanks, that was helpful, but it does not totally apply to my case. I'm not so much interested in the mechanics of sending XML as I am in obtaining the existing encoding of the `XDocument` that contains the `XElement` I am sending in the request. – Tony Vitabile Aug 05 '13 at 13:43
  • But your element enconde is different from the main document encode? I dont got this! – Fals Aug 05 '13 at 13:45
  • No, it's not different. The XML didn't originate in my code, it was sent to me from the same service I'm sending it back to. My application queries for the XML, receives it, and displays it. The user can modify the data and I send the modified XML back. When I write the XML, I have to create a new `XmlTextWriter` to write the XML to the request stream. I have to specify an encoding in that declaration. Where do I get the `XDocument`'s encoding so I can pass it when creating the `XmlTextWriter`? – Tony Vitabile Aug 05 '13 at 13:53

1 Answers1

1

After digging into the documentation a little deeper than I had before, I found the answer.

The XDocument class has a property called Declaration, which is of type XDeclaration. The XDeclaration object has a property called Encoding which has the information I need.

I just need to persist that property so I can pass it to the XmlTextWriter constructor.

Tony Vitabile
  • 8,298
  • 15
  • 67
  • 123