本文介绍了配置的ASP.NET Web API发送空值空标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的ASP.NET Web API。

I am new to ASP.NET Web API.

我已经配置我的应用程序使用的XMLSerializer为

I have configured my application to use XMLSerializer as

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

有关简单说,我的控制器返回Account类的一个实例

For Simplicity say my Controller returns an instance of class 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 的(这是可选)为

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

XML输出​​跳过的 AccountNickName 的标签,如果该值为null。

the XML output skips the AccountNickName tag if the value is null.

我的问题是:


  1. 如何配置串行发送一个封闭的标签,而不是跳过财产

  1. How do I configure the serializer to send a closed tag instead of skipping the property

和有没有在应用层,而不是在类级别

AND Is there a way to configure this on the application level rather than on the class level

更新:

我知道,你可以通过使用,你能以某种方式做到这一点用的XMLSerializer呢?

I know that you can configure the JsonFormatter by using a JsonSerializerSetting, Can you somehow do this with XMLSerializer as well?

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

I DO NOT want to add Attributes / Decorators on the Class.

推荐答案

XmlSerializer的会写出来的财产,如果你把这个在你的财产,即使它为空: [XmlElement的(ISNULLABLE =真)]

The XmlSerializer will write out the property even when it's null if you put this on your property: [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>

这篇关于配置的ASP.NET Web API发送空值空标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 12:39