自定义XmlSerializer只在WebApi中添加名称空间

时间:2022-11-20 15:12:15

We're trying to remove all namespacing from our XML API responses. We're using a custom BufferedMediaTypeFormatter that looks like:

我们试图从XML API响应中删除所有名称空间。我们使用的自定义BufferedMediaTypeFormatter如下所示:

namespace HeyWorld.MediaTypeFormatters
{
    public class SectionMediaTypeFormatter : BufferedMediaTypeFormatter
    {
        public override bool CanReadType(Type type)
        {
            return typeof(SectionResponse) == type;
        }

        public override bool CanWriteType(Type type)
        {
            return typeof(SectionResponse) == type;
        }

        public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
        {
            var xmlWriterSettings = new XmlWriterSettings { OmitXmlDeclaration = true, Encoding = Encoding.UTF8 };

            using (XmlWriter writer = XmlWriter.Create(writeStream, xmlWriterSettings))
            {
                var namespaces = new XmlSerializerNamespaces();
                namespaces.Add(string.Empty, string.Empty);
                var serializer = new XmlSerializer(type);
                serializer.Serialize(writer, value, namespaces);
            }
        }

        public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var serializer = new XmlSerializer(type);
            return serializer.Deserialize(readStream);
        }
    }
}

As we understand it (from answers like this), that namespaces.Add(string.Empty, string.Empty); should remove all namespaces from any serialized XML. In unit tests, that's exactly what it does:

正如我们所理解的那样(从这样的答案中),那个名称空间。空,string.Empty);应该从任何序列化的XML中删除所有名称空间。在单元测试中,它就是这样做的:

[Test]
public void ShouldntDoNamespaces(){
     var sectionResponse = new SectionResponse("yes!");
     var sectionMediaTypeFormatter = new SectionMediaTypeFormatter();

     using (var memoryStream = new MemoryStream())
     {
         sectionMediaTypeFormatter.WriteToStream(typeof(T), sectionResponse, memoryStream, null);

            using (var reader = new StreamReader(memoryStream))
            {
                memoryStream.Position = 0;
                Assert.That(reader.ReadToEnd(), Is.EqualTo(
                    '<Section attribute="yes!"></Section>'
                );
            }
        }
}

However in the deployed application, it adds default namespaces!

但是在部署的应用程序中,它添加了默认名称空间!

GET /Section/21

<Section 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    attribute="yes!"></Section>

Maybe it's something configured in our Global.asax?:

也许是在我们的Global.asax中配置的。

    GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
    GlobalConfiguration.Configuration.Formatters.Insert(0, new SectionMediaTypeFormatter());

Any help getting rid of those would be greatly appreciated.

任何帮助摆脱这些将非常感谢。

1 个解决方案

#1


4  

Make sure to add the supported media types:

确保添加支持的媒体类型:

public class SectionMediaTypeFormatter : BufferedMediaTypeFormatter
{
    public SectionMediaTypeFormatter()
    {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
    }

Also I see that you want to still keep the default xml formatter...so you want this custom formatter to only apply to SectionResponse type and for all other types the default xml formatter should apply...is it?

我还看到,您仍然希望保留默认的xml格式化程序……因此,您希望这个自定义格式化程序只适用于SectionResponse类型,对于所有其他类型,应该应用默认的xml格式化程序……是吗?

#1


4  

Make sure to add the supported media types:

确保添加支持的媒体类型:

public class SectionMediaTypeFormatter : BufferedMediaTypeFormatter
{
    public SectionMediaTypeFormatter()
    {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
    }

Also I see that you want to still keep the default xml formatter...so you want this custom formatter to only apply to SectionResponse type and for all other types the default xml formatter should apply...is it?

我还看到,您仍然希望保留默认的xml格式化程序……因此,您希望这个自定义格式化程序只适用于SectionResponse类型,对于所有其他类型,应该应用默认的xml格式化程序……是吗?