-1

I am trying to create a web API that takes XML as an input. The problem is that the requests are encoded as ISO-8859-1.

At first I tried just using an XmlDocument parameter but it gave a 500 error when the encoding was wrong:

[HttpPost]
public IActionResult XmlEndpoint([FromBody] XmlDocument requestXmlBody)

Next I tried parsing it myself but this never closed the request properly and caused HTTP Clients to be connected forever when the XML was malformed.

[HttpPost]
public async Task<IActionResult> XmlEndpoint()
{
    using var stringReader = new StreamReader(Request.Body, dataEncodingFromByteOrderMarks: true))
    var body = await stringReader.ReadToEndAsync();
    var requestXmlBody = new XmlDocument();
    requestXmlBody.LoadXml(body);

Afterwards I tried using the ASP.NET Core functionallity part-way, however this gives Unsupported Media Type when ISO-8599-1 is used:

[HttpPost]
public async Task<IActionResult> XmlEndpoint([FromBody] string content)
{
    var requestXmlBody = new XmlDocument();
    requestXmlBody.LoadXml(content);

This is the command I used for testing:

curl -XPOST 'https://localhost/api/XmlEndpoint' --data "<broken</broken>" -H "Content-Type: application/xml;charset=iso-8859-1"

How can I get an XMLDocument from the ISO-8859-1 encoded request?

Redline
  • 441
  • 8
  • 20
  • 2
    Why not specify `System.Text.Encoding.Latin1` in your StreamReader? This "never closed the request properly" shouldn't happen, and you probably just had a bug in your controller. – David Browne - Microsoft Sep 08 '21 at 14:12
  • @DavidBrowne-Microsoft `System.Text.Encoding.Latin1` Doesn't exist anywhere I can find but I did find `Encoding.GetEncoding("ISO-8859-1")`. Thank you for hinting that it isn't this code but something else, I wrote an answer to what fixed my problem. – Redline Sep 08 '21 at 15:57

1 Answers1

0

I managed to fix attempt 2. into working. The reason I had it never closed the connection properly was because I had a custom middleware that broke because the StreamReader closed the stream.

So in the end the solution that worked for me is:

[HttpPost]
public async Task<IActionResult> WriteXmlToFile()
{
    using var stringReader = new StreamReader(Request.Body, Encoding.GetEncoding("ISO-8859-1"), leaveOpen: true);
    var body = await stringReader.ReadToEndAsync();

    var requestXmlBody = new XmlDocument();
    requestXmlBody.LoadXml(body);

Thank you to @DavidBrowne-Microsoft for making me aware that it shouldn't be this code that makes the connection hang but something else.

Redline
  • 441
  • 8
  • 20