Allow .NET WebApi to disregard DOCTYPE declaration

余生长醉 提交于 2019-12-14 02:59:12

问题


I am trying to deserialize XML to an object through a WebApi Method.

I have the following class:

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

And the following Method in a WebApi Controller.

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

I am using the XmlSerializer by setting the following in the startup of the Web Project:

config.Formatters.XmlFormatter.UseXmlSerializer = true;

When I POST the following XML, the model is correctly deserialized, and I can read the properties of it.

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

However, when I POST the XML with a DOCTYPE declaration, the model value is null and seemingly not being deserialized on method-entry. I.e. this XML does not deserialize to a model:

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

Hope someone is able to help.


回答1:


Even if is an old post, I found myself in the same situation. I ended up in writing a customized version of the XmlMediaTypeFormatter overriding the ReadFromStreamAsync method.

Here my personal solution:

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);
        }
    }
}

Then obviously I've replaced the standard XmlFormatter of my configuration:

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



回答2:


I have not tried it with DOCTYPEs but implementing the IXmlSerializable interface should give you full control over the object serialization by the XmlSerializer.

IXmlSerializable Interface



来源:https://stackoverflow.com/questions/26228371/allow-net-webapi-to-disregard-doctype-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!