2

I have written a simple webAPI program which returns JSON by default when running , I want the values in XML format so I tried multiple answers from this stackoverflow post but all of them returns String for me

Model class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace JsonToXML2.Models
{
    public class Employee
    {
        public int EmployeeId
        {
            get;
            set;
        }
        public string EmployeeName
        {
            get;
            set;
        }
        public string Address
        {
            get;
            set;
        }
        public string Department
        {
            get;
            set;
        }
    }
}

Controller Class :

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Xml;
using System.Xml.Serialization;

namespace JsonToXML2.Controllers
{
    public class EmployeeController : ApiController
    {
        IList<Employee> employees = new List<Employee>()
        {
            new Employee()
                {
                    EmployeeId = 1, EmployeeName = "Mukesh Kumar", Address = "New Delhi", Department = "IT"
                },
                new Employee()
                {
                    EmployeeId = 2, EmployeeName = "Banky Chamber", Address = "London", Department = "HR"
                },
                new Employee()
                {
                    EmployeeId = 3, EmployeeName = "Rahul Rathor", Address = "Laxmi Nagar", Department = "IT"
                },
                new Employee()
                {
                    EmployeeId = 4, EmployeeName = "YaduVeer Singh", Address = "Goa", Department = "Sales"
                },
                new Employee()
                {
                    EmployeeId = 5, EmployeeName = "Manish Sharma", Address = "New Delhi", Department = "HR"
                },
        };
        public IList<Employee> GetAllEmployees()
        {
            //Return list of all employees  
            return employees;
        }
        public String GetEmployeeDetails(int id)
        {
            //Return a single employee detail  
            var employee = employees.FirstOrDefault(e => e.EmployeeId == id);
            if (employee == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            
           
            return (GenerateXmlResponse(employee));
        }
        // override StringWriter
        public class Utf8StringWriter : StringWriter
        {
            public override Encoding Encoding => Encoding.UTF8;
        }

        private string GenerateXmlResponse(Object obj)
        {
            Type t = obj.GetType();

            var xml = "";

            using (StringWriter sww = new Utf8StringWriter())
            {
                using (XmlWriter writer = XmlWriter.Create(sww))
                {
                    var ns = new XmlSerializerNamespaces();
                    // add empty namespace
                    ns.Add("", "");
                    XmlSerializer xsSubmit = new XmlSerializer(t);
                    xsSubmit.Serialize(writer, obj, ns);
                    xml = sww.ToString(); // Your XML
                }
            }
            return xml;
        }
    }
}

To access the app I am simply hitting the URL as https://localhost:44379/api/employee/1 in postman, the problem is data is in String format within double quotes, How can I get the data in pure XML format?

enter image description here

Postman recognizes the response as JSON enter image description here

skr
  • 1,700
  • 1
  • 15
  • 39
  • 1
    The easiest is just to return the employee, and then the client have to decide what they want using the httpheader ("text/xml"), else they get the default (JSON). But I am unsure if you have enough control over the client to force that so I'll just leave this as a comment – Thomas Koelle Jun 29 '21 at 13:54
  • Hi @ThomasKoelle, I need to pass the data to a paymentGateway which accepts XML's only. – skr Jun 29 '21 at 13:58
  • 1
    Then add "Accept: text/xml" header to the request and return the plain object. ASP.NET will automatically format the response according to the header. – phuzi Jun 29 '21 at 14:00
  • @ThomasKoelle "Accept: text/xml" works but it misses the xml declaration. – skr Jun 29 '21 at 14:07
  • @phuzi setting "Accept: text/xml" works but it misses the xml declaration. – skr Jun 29 '21 at 14:09
  • Ironically I think custom XML seriliasation is the problem here. – phuzi Jun 29 '21 at 14:17
  • @phuzi, what do you mean by custom XML seriliasation? – skr Jun 29 '21 at 14:29
  • I mean `GenerateXmlResponse`. I would think there would be a serialisation option to include the XML declaration. – phuzi Jun 29 '21 at 14:52

1 Answers1

1

As I Discussed above one of the solution was to ask clients to set request header "Accept: text/xml"

Since I couldn't force the client, what I can do at my end is to set my method return type as System.Net.Http.HttpResponseMessage and use the below code to return the XML.

public HttpResponseMessage Authenticate()
{
  //process the request 
  .........

  string XML="<note><body>Message content</body></note>";
  return new HttpResponseMessage() 
  { 
    Content = new StringContent(XML, Encoding.UTF8, "application/xml") 
  };
}

Response :

enter image description here

skr
  • 1,700
  • 1
  • 15
  • 39