网络核心3 AddXmlSerializerFormatters()配置选项

时间:2020-02-20 14:28:49

标签: xml asp.net-core asp.net-core-webapi asp.net-core-3.0

应用程序需要能够在正在运行的Json和Xml中返回数据。但是,与此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.");
        }
    }
}

1 个答案:

答案 0 :(得分:4)

是否有一种方法可以使Net Core 3覆盖Webapi中的命名空间,而无需编写自定义序列化程序包装器?

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

您需要为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();