- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
应用程序需要能够返回工作中的 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/
应用程序需要能够返回工作中的 Json 和 Xml 格式的数据。但是,与此 api 交互的应用程序在其结果中不支持命名空间。 在此版本之前,我必须编写自定义 xml serilaiser 来为我执行
我是一名优秀的程序员,十分优秀!