net core 3 AddXmlSerializerFormatters() configure options
应用程序需要能够在正在运行的Json和Xml中返回数据。但是,与此API交互的应用程序在其结果中不支持名称空间。
以前,在此版本之前,我必须编写一个自定义xml serilaiser来为我做这件事:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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中的名称空间,而无需编写自定义序列化程序package器?
我的测试控制器如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | [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创建自定义序列化程序格式化程序,如下所示:
1 2 3 4 5 6 7 8 9 10 | 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:
1 2 3 4 | services.AddControllers(options => { options.OutputFormatters.Add(new XmlSerializerOutputFormatterNamespace()); }).AddXmlSerializerFormatters(); |