[英]Deserializing XML in Asp.NET Core MVC
我正在嘗試為我的一個控制器的ASP.Net Core管道添加自定義xml反序列化器。 我已經能夠像這樣對JSON執行此操作:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.RespectBrowserAcceptHeader = true;
// Input formatters
var xmlInputFormatting = new XmlDataContractSerializerInputFormatter();
var jsonInputFormatting = new JsonInputFormatter();
jsonInputFormatting.SerializerSettings.Converters.Add(new BatchContentConverter());
options.InputFormatters.Clear();
options.InputFormatters.Add(jsonInputFormatting);
options.InputFormatters.Add(xmlInputFormatting);
}
}
(為簡潔起見,已刪除了許多不必要的代碼)。
該結束的控制器動作是:
public IActionResult Post([FromBody]IBatchContent batchContent)
{
}
是否可以使用XMLSerializerInputFormatter或XmlDataContractSerializerInputFormatter對XML做類似的事情? 我嘗試過創建一個從DataContractResolver派生的類,並將其分配給SerializerSettings.DataContractResolver屬性,但它似乎從未被調用過。
默認情況下, 不添加Xml格式器。 您需要包括Microsoft.AspNetCore.Mvc.Formatters.Xml
軟件包,其中包含XmlSerializerInputFormatter,XmlSerializerOutputFormatter,XmlDataContractSerializerInputFormatter和XmlDataContractSerializerOutputFormatter
您只需要執行以下操作:
創建一個從“ Microsoft.AspNetCore.Mvc.Formatters”命名空間中的“ XmlSerializerInputFormatter”類繼承的類,並覆蓋受保護的方法“ CreateSerializer”。 方法摘要指出“ [反序列化期間調用此方法以獲取System.Xml.Serialization.XmlSerializer”。
public class IBatchCollectionXmlSerializer : XmlSerializerInputFormatter { protected override XmlSerializer CreateSerializer(Type type) { //init expected type Type expectedType = typeof(IBatchContent); //init xml serializer XmlSerializer serializer = null; //if not expected type if (expectedType != type) { //return default serializer serializer = base.CreateSerializer(type); } //if expected type else { //add concrete type to deserialize to Type[] extraTypes = new Type[] { typeof (BatchContentConcrete) }; //create custom xml serializer here serializer = new XmlSerializer(typeof(IBatchContent), extraTypes); } //return serializer return serializer; } }
在Startup.cs文件中的mvc服務配置過程中將此添加到輸入格式化程序
services.Configure<MvcOptions>(options => { options.RespectBrowserAcceptHeader = true; // Input formatters var xmlInputFormatting = new IBatchCollectionXmlSerializer(); var jsonInputFormatting = new JsonInputFormatter(); jsonInputFormatting.SerializerSettings.Converters.Add(new BatchContentConverter()); options.InputFormatters.Clear(); options.InputFormatters.Add(jsonInputFormatting); options.InputFormatters.Add(xmlInputFormatting); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.