Configure ASP.NET Web API to send empty tags for null values

非 Y 不嫁゛ 提交于 2019-12-11 04:48:49

问题


I am new to ASP.NET Web API.

I have configured my application to use XMLSerializer as

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

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

I get this when as XML response when AccountNickName (which is optional) has a value

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

I get this as XML response when AccountNickName (which is optional) is null

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

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

My question are :

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

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

Update:

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.


回答1:


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>



回答2:


Did a quick test here and I found that if you don't do this:

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

The null value will get serialized as an actual element by default.

Is there another reason why you explicitly wanted to configure this? Setting that value to "true" will cause Web API to use the "XmlSerializer" instead of the "DataContractSerialier" class which is the default.

Web API will return XML for a given request if the request includes the appropriate "Content-Type" header indicating the desire for an XML response.



来源:https://stackoverflow.com/questions/13883031/configure-asp-net-web-api-to-send-empty-tags-for-null-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!