c# – Ignore XML namespace when modelbinding in asp net core web api

So, in order to be able to modelbind XML to a class without taking namespaces into consideration I created new InputFormatter. And I use XmlTextReader in order to ignore namespaces. Microsoft recommends to use XmlReader rather than XmlTextReader. But since XmlTextReader is there still (in .Net 6.0 Preview 3) I’ll use it for now.

Simply create an inputformatter that inherits from XmlSerializerInputFormatter like so:

public class XmlNoNameSpaceInputFormatter : XmlSerializerInputFormatter
{
    private const string ContentType = "application/xml";
    public XmlNoNameSpaceInputFormatter(MvcOptions options) : base(options)
    {
        SupportedMediaTypes.Add(ContentType);
    }

    public override bool CanRead(InputFormatterContext context)
    {
        var contentType = context.HttpContext.Request.ContentType;
        return contentType.StartsWith(ContentType);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
    {
        var type = GetSerializableType(context.ModelType);
        var request = context.HttpContext.Request;

        using (var reader = new StreamReader(request.Body))
        {
            var content = await reader.ReadToEndAsync();
            Stream s = new MemoryStream(Encoding.UTF8.GetBytes(content));

            XmlTextReader rdr = new XmlTextReader(s);
            rdr.Namespaces = false;
            var serializer = new XmlSerializer(type);
            var result = serializer.Deserialize(rdr);
            return await InputFormatterResult.SuccessAsync(result);
        }
    }
}

Then add it to the inputformatters like so to startup.cs:

        services.AddControllers(o => 
        {
            o.InputFormatters.Add(new XmlNoNameSpaceInputFormatter(o));
        })
        .AddXmlSerializerFormatters();

Now we can modelbind Person or any other class no matter if there is namespaces or not in the incoming XML. Thanks to @yiyi-you

Source: c# – Ignore XML namespace when modelbinding in asp net core web api – Stack Overflow

One thought on “c# – Ignore XML namespace when modelbinding in asp net core web api”

Leave a Reply

Your email address will not be published. Required fields are marked *