2

我是 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;}
}

当AccountNickName(可选)具有值时,我得到这个作为 XML 响应

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

AccountNickName(可选)为null

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

如果值为 null,则 XML 输出会跳过AccountNickName标记。

我的问题是:

  1. 如何配置序列化程序以发送封闭标签而不是跳过属性

  2. 并且有没有办法在应用程序级别而不是在类级别上配置它

更新:

我知道您可以使用 JsonSerializerSetting 来配置 JsonFormatter ,您也可以使用XMLSerializer来做到这一点吗?

我不想在类上添加属性/装饰器。

4

2 回答 2

1

在这里做了一个快速测试,我发现如果你不这样做:

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

默认情况下,null 值将被序列化为实际元素。

您明确想要配置它还有另一个原因吗?将该值设置为“true”将导致 Web API 使用“XmlSerializer”而不是默认的“DataContractSerialier”类。

如果请求包含适当的“Content-Type”标头,表明需要 XML 响应,Web API 将为给定请求返回 XML。

于 2012-12-14T17:56:16.813 回答
0

如果你把它放在你的属性上,即使它为 null,XmlSerializer 也会写出该属性: [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>
于 2012-12-14T19:26:41.617 回答