using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.Formatters; namespace Win_in.Sfs.Scp.WebApi.XmlHost { public class XDocumentInputFormatter : InputFormatter, IInputFormatter, IApiRequestFormatMetadataProvider { private Type currentType { get; set; } public XDocumentInputFormatter() { SupportedMediaTypes.Add("application/xml"); } protected override bool CanReadType(Type type) { currentType = type; if (type.IsAssignableFrom(typeof(XDocument))) return true; return base.CanReadType(type); } public override async Task ReadRequestBodyAsync(InputFormatterContext context) { // Use StreamReader to convert any encoding to UTF-16 (default C# and sql Server). using var streamReader = new StreamReader(context.HttpContext.Request.Body); var xmlDoc = await XDocument.LoadAsync(streamReader, LoadOptions.None, CancellationToken.None); var model = new XmlSerializer(currentType).Deserialize(xmlDoc.CreateReader()); return await InputFormatterResult.SuccessAsync(model); } } }