2012-12-14 35 views
1

我是ASP.NET Web API的新手。配置ASP.NET Web API以發送空值的空標記

我已經配置我的應用程序使用的XMLSerializer爲

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer 
                    = true; 

爲了簡單說,我的控制器返回Account類的一個實例

public class Account 
{ 
    public int AccountId {get;set;} 

    public string AccountName {get;set;} 

    public string AccountNickName {get;set;} 
} 

我得到這個時候作爲XML響應時AccountNickName(這是可選的)具有值

<Account> 
<AccountId>1</AccountId> 
<AccountName>ABAB</AccountName> 
<AccountNickName>My Account</AccountNickName> 
</Account> 

我得到這個作爲XML響應時AccountNickName(這是可選的)是null

<Account> 
<AccountId>1</AccountId> 
<AccountName>ABAB</AccountName> 
</Account> 

XML輸出跳過AccountNickName標籤,如果該值爲null。

我的問題是:

  1. 如何配置串行發送一個封閉的標籤,而不是跳過財產

  2. 的,並沒有對應用程序級別配置此相當的方式比類級別

更新:

我知道你可以通過使用JsonSerializerSetting來配置JsonFormatter,你是否也可以用XMLSerializer做到這一點?

我不想在Class上添加Attributes/Decorators。

+0

這似乎是一個性能的提高,而不是退後一步上表現我只是相應地調整我的客戶。只要你有客戶的控制權。 – Ulises

+0

爲什麼客戶關心空標籤與自閉元素? –

+0

這不是關於空或自我關閉。輸出中不存在標籤! – frictionlesspulley

回答

0

在這裏做了一個快速測試,我發現,如果你不這樣做:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer                 = true; 

的空值將得到系列化因爲默認情況下的實際元素。

你有明確想要配置它的另一個原因嗎?將該值設置爲「true」將導致Web API使用「XmlSerializer」而不是默認的「DataContractSerialier」類。

如果請求包含指示希望獲得XML響應的相應「Content-Type」標頭,則Web API將爲給定請求返回XML。

+0

是的,我不想DataContract屬性的類和默認的DataContractSerializer添加到我的集合dp4命名空間..這裏給出的例子是簡化 – frictionlesspulley

+0

「我不希望DataContract屬性的類」=>注意DataContractSerializer具有POCO類型支持... –

+0

即使我將這個mlserializer添加到true,它仍然不會返回null xml元素。 – chinnu

1

如果將此屬性放在屬性中,則XmlSerializer將寫出該屬性,即使該屬性爲null:[XmlElement(IsNullable = true)]

public class Account 
{ 
    public int AccountId { get; set; } 
    public string AccountName { get; set; } 

    [XmlElement(IsNullable = true)] 
    public string AccountNickName { get; set; } 
} 

XML:

<Account xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <AccountId>123</AccountId> 
    <AccountName>John Doe</AccountName> 
    <AccountNickName xsi:nil="true"/> 
</Account> 
+0

有沒有辦法在應用程序級別而不是在類級別上對其進行配置? – frictionlesspulley

+0

您可以使用'XmlAttributesOverrides'將'IsNullable'設置爲'true',然後將'XmlAttributesOverrides'添加到'config.Formatters.XmlFormatter.SetSerializer'中的序列化程序中,但這隻適用於您的屬性不是原始類型(即'AccountNickName'是你的代碼片段中的字符串)。 –