Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Tomasz Kowalski 135 posts 445 karma points
    Jul 03, 2016 @ 20:54
    Tomasz Kowalski
    0

    UmbracoApiController - output as XML (not JSON)

    Hi,

    I have an UmbracoApiController with a method that returns a list of products.

    public class productsApiController : UmbracoApiController
    {
        [System.Web.Http.HttpGet]
        public IEnumerable<ProductModel> getProducts()
        {
            List<ProductModel> result = new List<ProductModel>();
    
            //get products code goes here ...
    
            return result;
        }
    

    }

    As expected, output is in JSON.

    Is there a simple way to change output to XML?

    Regards Thomas

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Jul 03, 2016 @ 22:38
    Alex Skrypnyk
    0

    Hi Thomas,

    The Web API controller can automatically determine what format to return the data from the controller, usually this is will be JSON or XML. This is determined by the 'Accept' header that is sent during the request which can be set to 'application/xml' or 'application/json'.

    For sure you need to add custom formatter at global asax.

    public class CustomGlobal : UmbracoApplication
        {
            private void application_PreRequestHandlerExecute(object sender, EventArgs e)
            {
                var formatters = GlobalConfiguration.Configuration.Formatters;
                formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            }
        }
    

    More info at http://stackoverflow.com/questions/35129536/return-json-as-default-from-umbraco-api-controller

    Thanks,

    Alex

  • Tomasz Kowalski 135 posts 445 karma points
    Jul 04, 2016 @ 19:18
    Tomasz Kowalski
    100

    Hi Alex,

    Thanks for your answer, but I want only this one method to return always XML.

    I've ended up with this:

     [System.Web.Http.HttpGet]
        public HttpResponseMessage getProductsAsXml()
        {
             //...
             XDocument nodesXML = new XDocument(new XElement("Products",
                from product ...
                )
            ));
    
            return new HttpResponseMessage() { Content = new StringContent(nodesXML.ToString(), Encoding.UTF8, "application/xml") };
        }
    
    }
    

    Regards Thomas

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Jul 04, 2016 @ 19:50
    Alex Skrypnyk
    0

    Hi Thomas,

    Glad that you solve your issue.

    You also can remove json formatter and leave only xml:

    var formatters = GlobalConfiguration.Configuration.Formatters;
    
    formatters.Remove(formatters.XmlFormatter);
    

    It will be the same, but more readable controllers code.

    Thanks,

    Alex

Please Sign in or register to post replies

Write your reply to:

Draft