1

I am building an API using the WebAPI in ASP.NET MVC 4.0. I have built model classes based on sample XML supplied by my Business Analyst using the new, super smart Paste XML as Classes feature.

The problem is, when my client Accepts application/xml, the serialized response doesn't look like the original XML.

I have manually deserialized and serialized some XML (roundtrip) using the XMLSerializer, and although its better, closer to the original, it still lacks some namespace prefixes.

How can I ensure the output is exactly on spec.?

1 Answer 1

2

Firstly, you'll need to ensure the WebAPI is using the XmlSerializer to format your WebAPI responses, or at least use the XmlSerializer just for this resource/API.

In the WebApiConfig.cs file you'll find the route registration stuff and also some commented-out code.

Add under that chunk, add the following:

var xmlSerializer = new XmlSerializer(typeof(FruitXmlModel));
config.Formatters.XmlFormatter.SetSerializer<FruitXmlModel>(xmlSerializer);

This will specify the old XmlSerializer be used when serializing the FruitXmlModel CLR type. Note that you'll probably need to reference the XML serialization assemblies.

Next, you'll need to add this code to the class in your model that represents the element in your XML that begins the new namespace.

...

[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces();

public FruitXmlModel() // ctor for one of my models
{
    this.Namespaces.Add("banana", "http://www.fruitschema.org/banana");
}

...

If you've used the Paste XML as Classes feature, then this class should already be annotated with the correct attributes XmlTypeAttribute with the correct namespace set.

All being well, this simple change will provide the WebAPI and the XmlSerializer all that's needed to produce the properly prefixed XML output.

I wish you good luck, Luke, hope to meet again soon.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.