gpt4 book ai didi

xml - net core 3 AddXmlSerializerFormatters() 配置选项

转载 作者:行者123 更新时间:2023-12-05 08:51:09 24 4
gpt4 key购买 nike

应用程序需要能够返回工作中的 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 中的命名空间,而无需编写自定义序列化程序包装器?

我的测试 Controller 如下所示:

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

启动.cs:

services.AddControllers(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatterNamespace());
}).AddXmlSerializerFormatters();

关于xml - net core 3 AddXmlSerializerFormatters() 配置选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60322216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com