Dotnet Core Model Binding XML with Serializable Attribute encoding

Viewed 169

I have a dotnet core 3.1 project with multiple controllers and api routes. In one of my controllers I have a Post method that expects a specific model from the body.

PostThatThing([FromBody] CarModel carRequest, ...)

Say CarModel looks like this:

// A test object that needs to be serialized.
[Serializable()]
public class CarModel {

    public string Engine {get; set;}
    public string Color {get; set;}

}

If I send a post request to the endpoint like so:

<?xml version="1.0" encoding="UTF-8"?>
<CarModel>
    <Engine>Hemi 5.7</Engine>
    <Color>Black</Color>
</CarModel>

It works with no issue, the request is serialized and binds to CarModel, thus allowing me to use carRequest.

The issue has to do with encoding.

If I switch out the encoding value to be this: us-ascii (Or anything other than utf-8)

<?xml version="1.0" encoding="us-ascii"?>
<CarModel>
    <Engine>Hemi 5.7</Engine>
    <Color>Black</Color>
</CarModel>

Then the binding fails and tells me: "The encoding in the declaration 'us-ascii' does not match the encoding of the document 'utf-8'"

As far as I can tell, ascii is a subset of utf-8, so it should have no problem translating anything.

I tried adding Default Encoders to XmlReaderSettings in startup with .Configure<MvcOptions>(...) I tried setting the encoder in XmlWritterSettings in startup with .Configure<MvcOptions>(...)

No luck. Same error as above.

Am I missing something obvious with how xml serialization and encoding works? Also, just to note, I cannot control the request. I was told I have to be able to support us-ascii and one other (can't remember at the moment).

To note, this question is just like this one: Web API not able to bind model for POST with utf-16 encoded XML

0 Answers
Related