net core 3 AddXmlSerializerFormatters() 配置选项

net core 3 AddXmlSerializerFormatters() configure options

应用程序需要能够在 Json 和 Xml 中 return 工作的数据。但是,与此 api 交互的应用程序在其结果中不支持命名空间。 <Item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

在此版本之前,我不得不编写自定义 xml serilaiser 来为我执行此操作:

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;
        }

我正在使用 .AddXmlSerializerFormatters();但是在启动时它会生成命名空间。 有没有办法让 net core 3 覆盖 webapi 中的命名空间,而无需编写自定义序列化程序包装器?

我的测试控制器如下所示:

[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.");
        }
    }
}

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?

默认序列化器中没有这种方式。

您需要为 xml 创建自定义序列化程序格式化程序,如下所示:

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();