允许.NET Web Api忽略DOCTYPE声明

时间:2014-10-07 04:03:40

标签: c# xml asp.net-web-api xml-serialization asp.net-web-api2

我正在尝试通过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
 }

我通过在Web项目的启动中设置以下内容来使用XmlSerializer

config.Formatters.XmlFormatter.UseXmlSerializer = true;

当我发布以下XML时,model被正确反序列化,我可以读取它的属性。

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

但是,当我使用DOCTYPE声明POST XML时,model值为null,并且似乎没有在方法入口上反序列化。即此XML不会反序列化为模型:

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

希望有人能够提供帮助。

2 个答案:

答案 0 :(得分:4)

即使是一个老帖子,我发现自己处于同样的境地。我最终编写了一个自定义版本的 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());

答案 1 :(得分:0)

我没有尝试使用DOCTYPE,但实现IXmlSerializable接口应该可以让您完全控制XmlSerializer对象的序列化。

IXmlSerializable Interface