2

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

Pezetter
  • 2,783
  • 2
  • 22
  • 40
  • 1
    The error already tells you what's wrong. The document is encoded with utf8 but it expects us-ascii. Do some googling on how to change the encoding of a file (can be done with Notepad++ for example). This has nothing to do with subset or anything. – Aaron Sep 23 '20 at 05:07
  • 1
    @Aaron It’s coming in as a request from a client. It being a file and having differing encoding makes sense to me. I’m not sure how those relate. – Pezetter Sep 23 '20 at 05:09
  • 2
    `Serializable` has nothing to do with xml serialization fyi. – Daniel A. White Sep 23 '20 at 23:57
  • @DanielA.White Hmm didn't realize that. I think I'm a bit lost on serialization in general. Probably why this is an issue in the first place. – Pezetter Sep 24 '20 at 18:14

0 Answers0