prevent property from being serialized in web API

C#asp.netasp.net Mvcasp.net Web-Api

C# Problem Overview


I'm using an MVC 4 web API and asp.net web forms 4.0 to build a rest API. It's working great:

[HttpGet]
public HttpResponseMessage Me(string hash)
{
    HttpResponseMessage httpResponseMessage;
    List<Something> somethings = ...

    httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, 
                                 new { result = true, somethings = somethings });

    return httpResponseMessage;
}

Now I need to prevent some properties to be serialized. I know I can use some LINQ over the list and get only the properties I need, and generally it's a good approach, but in the present scenario the something object is too complex, and I need a different set of properties in different methods, so it's easier to mark, at runtime, each property to be ignored.

Is there a way to do that?

C# Solutions


Solution 1 - C#

ASP.NET Web API uses Json.Net as default formatter, so if your application just only uses JSON as data format, you can use [JsonIgnore] to ignore property for serialization:

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    [JsonIgnore]
    public List<Something> Somethings { get; set; }
}

But, this way does not support XML format. So, in case your application has to support XML format more (or only support XML), instead of using Json.Net, you should use [DataContract] which supports both JSON and XML:

[DataContract]
public class Foo
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string Name { get; set; }

    //Ignore by default
    public List<Something> Somethings { get; set; }
}

For more understanding, you can read the official article.

Solution 2 - C#

According to the Web API documentation page JSON and XML Serialization in ASP.NET Web API to explicitly prevent serialization on a property you can either use [JsonIgnore] for the Json serializer or [IgnoreDataMember] for the default XML serializer.

However in testing I have noticed that [IgnoreDataMember] prevents serialization for both XML and Json requests, so I would recommend using that rather than decorating a property with multiple attributes.

Solution 3 - C#

Instead of letting everything get serialized by default, you can take the "opt-in" approach. In this scenario, only the properties you specify are allowed to be serialized. You do this with the DataContractAttribute and DataMemberAttribute, found in the System.Runtime.Serialization namespace.

The DataContactAttribute is applied to the class, and the DataMemberAttribute is applied to each member you want to be serialized:

[DataContract]
public class MyClass {

  [DataMember]
  public int Id { get; set;} // Serialized

  [DataMember]
  public string Name { get; set; } // Serialized

  public string DontExposeMe { get; set; } // Will not be serialized
}

Dare I say this is a better approach because it forces you to make explicit decisions about what will or will not make it through serialization. It also allows your model classes to live in a project by themselves, without taking a dependency on JSON.net just because somewhere else you happen to be serializing them with JSON.net.

Solution 4 - C#

This worked for me: Create a custom contract resolver which has a public property called AllowList of string array type. In your action, modify that property depending on what the action needs to return.

1. create a custom contract resolver:

public class PublicDomainJsonContractResolverOptIn : DefaultContractResolver
{
    public string[] AllowList { get; set; }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

        properties = properties.Where(p => AllowList.Contains(p.PropertyName)).ToList();
        return properties;
    }
}

2. use custom contract resolver in action

[HttpGet]
public BinaryImage Single(int key)
{
    //limit properties that are sent on wire for this request specifically
    var contractResolver = Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver as PublicDomainJsonContractResolverOptIn;
    if (contractResolver != null)
        contractResolver.AllowList = new string[] { "Id", "Bytes", "MimeType", "Width", "Height" };

    BinaryImage image = new BinaryImage { Id = 1 };
    //etc. etc.
    return image;
}

This approach allowed me to allow/disallow for specific request instead of modifying the class definition. And if you don't need XML serialization, don't forget to turn it off in your App_Start\WebApiConfig.cs or your API will return blocked properties if the client requests xml instead of json.

//remove xml serialization
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

Solution 5 - C#

I will show you 2 ways to accomplish what you want:

First way: Decorate your field with JsonProperty attribute in order to skip the serialization of that field if it is null.

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<Something> Somethings { get; set; }
}

Second way: If you are negotiation with some complex scenarios then you could use the Web Api convention ("ShouldSerialize") in order to skip serialization of that field depending of some specific logic.

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
        
    public List<Something> Somethings { get; set; }

    public bool ShouldSerializeSomethings() {
		 var resultOfSomeLogic = false;
         return resultOfSomeLogic; 
	}
}

WebApi uses JSON.Net and it use reflection to serialization so when it has detected (for instance) the ShouldSerializeFieldX() method the field with name FieldX will not be serialized.

Solution 6 - C#

I'm late to the game, but an anonymous objects would do the trick:

[HttpGet]
public HttpResponseMessage Me(string hash)
{
    HttpResponseMessage httpResponseMessage;
    List<Something> somethings = ...

    var returnObjects = somethings.Select(x => new {
        Id = x.Id,
        OtherField = x.OtherField
    });

    httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, 
                                 new { result = true, somethings = returnObjects });

    return httpResponseMessage;
}

Solution 7 - C#

Try using IgnoreDataMember property

public class Foo
    {
        [IgnoreDataMember]
        public int Id { get; set; }
        public string Name { get; set; }
    }

Solution 8 - C#

Works fine by just adding the: [IgnoreDataMember]

On top of the propertyp, like:

public class UserSettingsModel
{
    public string UserName { get; set; }
    [IgnoreDataMember]
    public DateTime Created { get; set; }
}

This works with ApiController. The code:

[Route("api/Context/UserSettings")]
    [HttpGet, HttpPost]
    public UserSettingsModel UserSettings()
    {
        return _contextService.GetUserSettings();
    }

Solution 9 - C#

Almost same as greatbear302's answer, but i create ContractResolver per request.

  1. Create a custom ContractResolver

    public class MyJsonContractResolver : DefaultContractResolver { public List> ExcludeProperties { get; set; }

     protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
     {
         JsonProperty property = base.CreateProperty(member, memberSerialization);
    
         if (ExcludeProperties?.FirstOrDefault(
             s => s.Item2 == member.Name && s.Item1 == member.DeclaringType.Name) != null)
         {
             property.ShouldSerialize = instance => { return false; };
         }
    
         return property;
     }
    

    }

  2. Use custom contract resolver in action

    public async Task Sites() { var items = await db.Sites.GetManyAsync();

     return Json(items.ToList(), new JsonSerializerSettings
     {
         ContractResolver = new MyJsonContractResolver()
         {
             ExcludeProperties = new List<Tuple<string, string>>
             {
                 Tuple.Create("Site", "Name"),
                 Tuple.Create("<TypeName>", "<MemberName>"),
             }
         }
     });
    

    }

Edit:

It didn't work as expected(isolate resolver per request). I'll use anonymous objects.

public async Task<IActionResult> Sites()
{
    var items = await db.Sites.GetManyAsync();

    return Json(items.Select(s => new
    {
        s.ID,
        s.DisplayName,
        s.Url,
        UrlAlias = s.Url,
        NestedItems = s.NestedItems.Select(ni => new
        {
            ni.Name,
            ni.OrdeIndex,
            ni.Enabled,
        }),
    }));
}

Solution 10 - C#

You might be able to use AutoMapper and use the .Ignore() mapping and then send the mapped object

CreateMap<Foo, Foo>().ForMember(x => x.Bar, opt => opt.Ignore());

Solution 11 - C#

For .NET Core 3.0 and above:

> The default JSON serializer for ASP.NET Core is now System.Text.Json, which is new in .NET Core 3.0. Consider using System.Text.Json when possible. It's high-performance and doesn't require an additional library dependency.

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#newtonsoftjson-jsonnet-support

Sample (Thanks cuongle)

using System.Text.Json.Serialization;

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    [JsonIgnore]
    public List<Something> Somethings { get; set; }
}

If you already have Newtonsoft.Json intalled and chose to use it instead, by default, [JsonIgnore] won't work as expected.

Solution 12 - C#

For some reason [IgnoreDataMember] does not always work for me, and I sometimes get StackOverflowException (or similar). So instead (or in addition) i've started using a pattern looking something like this when POSTing in Objects to my API:

[Route("api/myroute")]
[AcceptVerbs("POST")]
public IHttpActionResult PostMyObject(JObject myObject)
{
    MyObject myObjectConverted = myObject.ToObject<MyObject>();

    //Do some stuff with the object

    return Ok(myObjectConverted);
}

So basically i pass in an JObject and convert it after it has been recieved to aviod problems caused by the built-in serializer that sometimes cause an infinite loop while parsing the objects.

If someone know a reason that this is in any way a bad idea, please let me know.

It may be worth noting that it is the following code for an EntityFramework Class-property that causes the problem (If two classes refer to each-other):

[Serializable]
public partial class MyObject
{
   [IgnoreDataMember]
   public MyOtherObject MyOtherObject => MyOtherObject.GetById(MyOtherObjectId);
}

[Serializable]
public partial class MyOtherObject
{
   [IgnoreDataMember]
   public List<MyObject> MyObjects => MyObject.GetByMyOtherObjectId(Id);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1330271View Question on Stackoverflow
Solution 1 - C#cuongleView Answer on Stackoverflow
Solution 2 - C#Michael MasonView Answer on Stackoverflow
Solution 3 - C#CBonoView Answer on Stackoverflow
Solution 4 - C#joym8View Answer on Stackoverflow
Solution 5 - C#foxhardView Answer on Stackoverflow
Solution 6 - C#Tim HoolihanView Answer on Stackoverflow
Solution 7 - C#KaviView Answer on Stackoverflow
Solution 8 - C#DannejahaView Answer on Stackoverflow
Solution 9 - C#tsu1980View Answer on Stackoverflow
Solution 10 - C#kenwarnerView Answer on Stackoverflow
Solution 11 - C#themefieldView Answer on Stackoverflow
Solution 12 - C#Arg0nView Answer on Stackoverflow