Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

net core 3 AddXmlSerializerFormatters() configure options

The application needs to be able to return data in both Json and Xml which is working. However, the application that is interfacing with this api does not support namespaces in it's result. <Item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

Previously before this version I have had to write a custom xml serilaiser to do this for me:

public static string Serialise<T>(T model) where T : class, new()
        {
            // Initalise the Xml writer with required settings.
            XmlWriterSettings settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true
            };
            // Set the namespaces accordingly.
            XmlSerializerNamespaces xmlNamespaceOverride = new XmlSerializerNamespaces();
            xmlNamespaceOverride.Add("", "");
            string xml = "";
            // Create a new string writer.
            using (StringWriter stringWriter = new StringWriter())
            {
                // And a new Xmlwriter.
                using (XmlWriter writer = XmlWriter.Create(stringWriter, settings))
                {
                    // Serialise the data.
                    new XmlSerializer(typeof(T)).Serialize(writer, model, xmlNamespaceOverride);
                    xml = stringWriter.ToString();
                }
            }
            return xml;
        }

I am using .AddXmlSerializerFormatters(); in the startup however it produces the namespace. Is there a way of getting net core 3 to override the namespace in a webapi without me having to write a custom serialiser wrapper?

A test controller i have looks like the following:

[Area("Api")]
[Route("test")]
[FormatFilter]
[Produces("application/json", "application/xml")]
public class DeleteMeController : BaseController
{
    public DeleteMeController(SpApiDbContext spApiDbContext) : base(spApiDbContext) { }

    [Route("{format}/{responseType?}")]
    [HttpGet]
    public async Task<ActionResult<List<Item>>> DeleteMe(string format, string responseType = null)
    {
        try
        {
            return responseType switch
            {
                "badrequest" => BadRequest(),
                "error" => throw new Exception(),
                "notfound" => NotFound(),
                "nocontent" => null,
                _ => new List<Item>()
                {
                    Item.Empty(),
                    Item.Empty()
                },
            };
        }
        catch(Exception exception)
        {
            return await ExceptionResponse(exception, "TEST, please ignore.");
        }
    }
}
like image 844
UncountedBrute Avatar asked Nov 30 '25 16:11

UncountedBrute


1 Answers

Is there a way of getting net core 3 to override the namespace in a webapi without me having to write a custom serialiser wrapper?

There is no such way in default serializer.

You need create custom serializer formatter for xml like below:

public class XmlSerializerOutputFormatterNamespace : XmlSerializerOutputFormatter
{
    protected override void Serialize(XmlSerializer xmlSerializer, XmlWriter xmlWriter, object value)
    {
        //applying "empty" namespace will produce no namespaces
        var emptyNamespaces = new XmlSerializerNamespaces();
        emptyNamespaces.Add("", "");
        xmlSerializer.Serialize(xmlWriter, value, emptyNamespaces);
    }
}

Startup.cs:

services.AddControllers(options =>
{
     options.OutputFormatters.Add(new XmlSerializerOutputFormatterNamespace());
}).AddXmlSerializerFormatters();
like image 163
Rena Avatar answered Dec 02 '25 06:12

Rena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!