【问题标题】:XML namespace missing in web api responseWeb api 响应中缺少 XML 命名空间
【发布时间】:2017-06-05 17:02:56
【问题描述】:

我有一个班级叫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; }    
}

网页接口代码

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

当我访问我的方法时,我得到如下响应:

<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>

我想获取命名空间信息作为响应。

我错过了什么?

<mcn:Customer xmlns:mcn="http://noatariff.com">
   <mcn:TimeReceived>2016-09-07T15:46:46.845-05:00</mcn:TimeReceived>
</mcn:Customer>

【问题讨论】:

  • 响应的“mcn”命名空间在哪里?你不能添加不存在的东西。看起来您正在添加自己的命名空间,因此您必须处理原始响应并进行修改以满足您的要求。
  • 看起来你实际上在使用DataContractSerializer。您是否尝试过通过[DataContract(Namespace = "http://noatariff.com")] 简单地在合同中设置命名空间,如here 所示?

标签: c# xml asp.net-web-api


【解决方案1】:

试试这个:

[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; }    
}

如果您使用DataContract 作为您的序列化程序,则不需要任何其他东西。

【讨论】:

    猜你喜欢
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多