ASP.Net return XML document from XNode with proper encoding

25 views Asked by At

I want to return an XML document represented as an XNode from asp.net

I have

public ContentResult SaveXml(XDocument doc, int statusCode){
    StringBuilder b = new();
    using var writer = new StringWriter(b);
    doc.Save(writer);

    return new ContentResult { Content = builder.ToString(), ContentType="text/xml", StatusCode = statusCode }
}

This returns an XML string that is UTF-8 encoded, but it has the tag <?xml encoding="utf-16" ?>, which makes my API consumers very confused and angry.

I think this happens because C# strings are utf16 so when the doc saves it sees its saving to a utf16 string and thinks "I must be saving to a UTF 16 string and will set my header accordingly"

The workaround I found was to change Content = builder.ToString() to Content = builder.ToString().Replace("utf-16","utf-8") but that's an extremely ugly hack.

Am I correct about the cause of this issue? If so how do I resolve this?

0

There are 0 answers