简体   繁体   中英

Web api - xml prefixes

Good day, by using web api, i need to get the following xml response (with all the prefixses):

  <test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ai="www.something.org">
    <ai:name>Ann</name>
    </test>

Here is the class:

[XmlRoot(ElementName = "test")]
    public class Test
    {
        [XmlAttribute(AttributeName = "ai")]
        public const string Ai = "www.something.org";
        [XmlElement(ElementName = "name",Namespace = Ai)]
        public string Name { get; set; }

        public Test(string name)
        {
            Name = name;
        }
        public Test() { }
    }

The thing is that if u use xmlSerializer on its own , u can use

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("ai", "www.something.org");

But here the serialization is made by web api request itself:

[HttpGet]
[Route("test")]
public Test Testing()
{
 return new Test("Ann");
}

What i'm getting is no ai attribute and no prefixses to namespaces.

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <name xmlns="www.something.org">
    Ann
    </name>

EDIT. If i overide the XmlMediaTypeFormatter , im getting the right xml response:

public class CustomXmlFormatter : XmlMediaTypeFormatter
    {
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
            TransportContext transportContext)
        {
            var serializer = new XmlSerializer(type);
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("ai", "www.something.org");

            return Task.Factory.StartNew(() =>
            {
                using (var streamWriter = new StreamWriter(writeStream, Encoding.UTF8))
                {
                    serializer.Serialize(streamWriter, value,ns);
                }
            });
            return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
        }
    }

But what if i have 2 requests, each of them have different namespaces - but this formatter will always show both of them. Is there any way to remove unused namespaces?

If you define your custom xml formatter like this:

public class CustomXmlFormatter : XmlMediaTypeFormatter
{
    public XmlSerializerNamespaces Namespaces { get; }

    public CustomXmlFormatter()
    {
        Namespaces = new XmlSerializerNamespaces();
    }

    public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        var serializer = new XmlSerializer(type);

        var xmlWriter = new XmlTextWriter(writeStream, Encoding.UTF8)
        {
            Namespaces = true
        };

        serializer.Serialize(xmlWriter, value, Namespaces);

        return Task.FromResult(true);
    }
}

You could then create a IControllerConfiguration that uses this formatter and adds your namespace:

public class MyControllerConfig : Attribute, IControllerConfiguration
{
    private readonly string _prefix;
    private readonly string _ns;

    public MyControllerConfig(string prefix, string ns)
    {
        _prefix = prefix;
        _ns = ns;
    }

    public void Initialize(HttpControllerSettings controllerSettings,
                            HttpControllerDescriptor controllerDescriptor)
    {
        var formatter = new CustomXmlFormatter { UseXmlSerializer = true };
        formatter.Namespaces.Add(_prefix, _ns);
        controllerSettings.Formatters.Clear();
        controllerSettings.Formatters.Add(formatter);
    }
}

And then use this on your controller:

[MyControllerConfig("ai", Ns.Ai)]
public class MyController : ApiController
{
    [HttpGet]
    [Route("test")]
    public IHttpActionResult Testing()
    {
        return Ok(new Test("Ann"));
    }
}

public class Ns
{
    public const string Ai = "www.something.org";
}

[XmlRoot(ElementName = "test")]
public class Test
{
    [XmlElement(ElementName = "name", Namespace = Ns.Ai)]
    public string Name { get; set; }

    public Test(string name)
    {
        Name = name;
    }
    public Test() { }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM