允许.NET的WebAPI忽略DOCTYPE声明(Allow .NET WebApi to disr

2019-10-21 03:04发布

我试图通过的WebAPI方法反序列化XML的一个对象。

我有以下类:

[XmlRoot(IsNullable = false)]
public class MyObject 
{
     [XmlElement("Name")]
     public string Name {get;set;}
}

并在控制器的WebAPI下面的方法。

 [HttpPost]
 public HttpResponseMessage UpdateMyObject(MyObject model)
 {
   //do something with the model
 }

我使用XmlSerializer通过设置Web项目的启动如下:

config.Formatters.XmlFormatter.UseXmlSerializer = true;

当我张贴下面的XML,该model是正确的反序列化,我可以看到它的属性。

<?xml version="1.0" encoding="UTF-8"?>
<MyObject>
    <Name>HelloWorld</Name>
</MyObject>

然而,当我发布的XML与DOCTYPE声明,该model值为空,看似不上法进入反序列化。 也就是说,该XML不反序列化到一个模型:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE MyObject SYSTEM "http://example.com/MyObject.dtd">
<MyObject>
    <Name>HelloWorld</Name>
</MyObject>

希望有人能够帮助。

Answer 1:

即使是旧的文章,我发现自己在同样的情况。 我在写XmlMediaTypeFormatter重写ReadFromStreamAsync方法的定制版本结束了。

在这里我个人的解决方案:

public class CustomXmlMediaTypeFormatter : XmlMediaTypeFormatter
{
    /// <summary>
    /// Initializes a new instance of the <see cref="CustomXmlMediaTypeFormatter"/> class.
    /// This XmlMediaTypeFormatter will ignore the doctype while reading the provided stream.
    /// </summary>
    public CustomXmlMediaTypeFormatter()
    {
        UseXmlSerializer = true;
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        if (type == null)
            throw new ArgumentNullException("type");
        if (readStream == null)
            throw new ArgumentNullException("readStream");

        try
        {
            return Task.FromResult(ReadFromStream(type, readStream, content, formatterLogger));
        }
        catch (Exception ex)
        {
            var completionSource = new TaskCompletionSource<object>();
            completionSource.SetException(ex);
            return completionSource.Task;
        }

    }

    private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        var httpContentHeaders = content == null ? (HttpContentHeaders)null : content.Headers;
        if (httpContentHeaders != null)
        {
            var contentLength = httpContentHeaders.ContentLength;
            if ((contentLength.GetValueOrDefault() != 0L ? 0 : (contentLength.HasValue ? 1 : 0)) != 0)
                return GetDefaultValueForType(type);
        }

        var settings = new XmlReaderSettings
        {
            DtdProcessing = DtdProcessing.Ignore
        };

        var deserializer = GetDeserializer(type, content);
        try
        {
            // The standard XmlMediaTypeFormatter will get the encoding from the HttpContent, instead
            // here the XmlReader will decide by itself according to the content
            using (var xmlReader = XmlReader.Create(readStream, settings))
            {
                var xmlSerializer = deserializer as XmlSerializer;
                if (xmlSerializer != null)
                    return xmlSerializer.Deserialize(xmlReader);

                var objectSerializer = deserializer as XmlObjectSerializer;
                if (objectSerializer == null)
                    throw new InvalidOperationException("xml object deserializer not available");

                return objectSerializer.ReadObject(xmlReader);
            }
        }
        catch (Exception ex)
        {
            if (formatterLogger == null)
            {
                throw;
            }

            formatterLogger.LogError(string.Empty, ex);
            return GetDefaultValueForType(type);
        }
    }
}

那么显然我已经取代我的配置标准XmlFormatter:

config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.Add(new CustomXmlMediaTypeFormatter());


Answer 2:

我还没有和文档类型尝试过,但实现IXmlSerializable接口应该给你在由对象序列完全控制XmlSerializer

IXmlSerializable的接口



文章来源: Allow .NET WebApi to disregard DOCTYPE declaration