1

I have a class called Customer

[Serializable]
[DataContract]
[XmlRoot(Namespace = "http://noatariff.com")]
public class Customer
{
    public Customer()
    {
        DateTime now = DateTime.Now;
        string datePart = now.ToString("yyyy-MM-dd");
        string timePart = now.ToString("HH:mm:ss.fffzzz");
        this.TimeReceived = String.Format("{0}T{1}", datePart, timePart);
    }

    [DataMember]
    [XmlElement(Namespace = "http://noatariff.com")]
    public string TimeReceived { get; set; }    
}

Web api code

    [HttpGet]
    [Route("ping")]
    public HttpResponseMessage GetCustomerTime()
    {
        Customer cust = new Customer();
        HttpResponseMessage resp = Request.CreateResponse<Customer>(HttpStatusCode.OK, cust, new XmlMediaTypeFormatter(), "application/xml");
        return resp;
    }

When I access my method, I get the response as follows:

<Customer xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PMPI_InterconnectService.Controllers">
    <TimeReceived>2016-09-07T15:35:50.658-05:00</TimeReceived>
    <head/>
</Customer>

I want to get the namespace information in response.

What I am missing?

<mcn:Customer xmlns:mcn="http://noatariff.com">
   <mcn:TimeReceived>2016-09-07T15:46:46.845-05:00</mcn:TimeReceived>
</mcn:Customer>
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42
  • https://stackoverflow.com/questions/17327677/xml-namespaces-in-asp-net-web-api – CodeCaster Jun 05 '17 at 17:05
  • Where is the 'mcn' namespace in response? You cannot add something that doesn't exist. It looks like you are adding your own namespace so you must process the original response and modify to meet your requirements. – jdweng Jun 05 '17 at 17:45
  • Possible duplicate of [XML Serialization and namespace prefixes](https://stackoverflow.com/q/2339782/1255289) – miken32 Jun 05 '17 at 18:14
  • It looks like you're actually using `DataContractSerializer`. Have you tried simply setting the namespace in the contract via `[DataContract(Namespace = "http://noatariff.com")]` as shown [here](https://stackoverflow.com/a/32114023/3744182)? – dbc Jun 06 '17 at 00:04

1 Answers1

0

just try this :

[DataContract(Namespace = "http://noatariff.com")]
public class Customer
{
    public Customer()
    {
        DateTime now = DateTime.Now;
        string datePart = now.ToString("yyyy-MM-dd");
        string timePart = now.ToString("HH:mm:ss.fffzzz");
        this.TimeReceived = String.Format("{0}T{1}", datePart, timePart);
    }

    [DataMember]
    public string TimeReceived { get; set; }    
}

if you are using DataContract as your serilizer you don't need any thing else.

Mohammad
  • 2,724
  • 6
  • 29
  • 55