Enum not coverting expando object to XML in .net Core Web API GET response

199 Views Asked by At

I have a get method on a .net Core 3.1 Web API controller that returns an expando object which is generated from a model class.

The model contains an enum value:

public class MyModel 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Gender Gender { get; set; }
}

public enum Gender
{
    Male,
    Female
}

[HttpGet("{id}")]
public async Task<IActionResult> GetAsync(int id)
{
    var recordFromDB = await dbService.GetAsync(id);

    if (recordFromDB == null)
        return NotFound();

    var returnModel = mapper.Map<MyModel>(recordFromDB).ShapeData(null);

    return Ok(returnModel);
}

public static ExpandoObject ShapeData<TSource>(this TSource source, string fields)
{
    var dataShapedObject = new ExpandoObject();

    if (string.IsNullOrWhiteSpace(fields))
    {
        var propertyInfos = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var propertyInfo in propertyInfos)
        {
            var propertyValue = propertyInfo.GetValue(source);

            ((IDictionary<string, object>)dataShapedObject).Add(propertyInfo.Name, propertyValue);
        }

        return dataShapedObject;
    }

    ... more of the method here but it's never hit so I've removed the code
}

If I do a get request for this record with the accept header application/json it all works fine.

if I change the accept header to application/xml I receive the following error:

System.Runtime.Serialization.SerializationException: Type 'Gender' with data contract name 'Gender' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

If I remove the enum value from the model the XML is generated fine.

Where do I add the KnownTypeAttribute or how do I get around this error?

Thanks in advance

0

There are 0 best solutions below