Reputation: 2691
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?
Upvotes: 194
Views: 202459
Reputation: 1547
IN .NET FRAMEWORK (NOT CORE)
USE [JsonIgnore]
FROM THE NAME SPACE using Newtonsoft.Json;
IT WILL WORK THAT WAY.
IF YOU USE [JsonIgnore]
FROM using System.Text.Json.Serialization;
IT WONT WORK.
Upvotes: 0
Reputation: 121
Use
[BindNever] //this means do NOT accept propert SecretPropert in url as parameter, neither do NOT show it in documentation of api such as swagger
public int SecretProperty { get; set; }
Upvotes: 0
Reputation: 4235
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.
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.
Upvotes: 6
Reputation: 109
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();
}
Upvotes: 10
Reputation: 3803
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.
Upvotes: 36
Reputation: 75306
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.
Upvotes: 259
Reputation: 2632
Almost same as greatbear302's answer, but i create ContractResolver per request.
1) Create a custom ContractResolver
public class MyJsonContractResolver : DefaultContractResolver
{
public List<Tuple<string, string>> 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<IActionResult> 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,
}),
}));
}
Upvotes: 6
Reputation: 8423
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 POST
ing 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);
}
Upvotes: 0
Reputation: 506
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.
Upvotes: 20
Reputation: 191
Try using IgnoreDataMember
property
public class Foo
{
[IgnoreDataMember]
public int Id { get; set; }
public string Name { get; set; }
}
Upvotes: 13
Reputation: 12396
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;
}
Upvotes: 18
Reputation: 4212
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);
Upvotes: 21
Reputation: 1390
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.
Upvotes: 121
Reputation: 29120
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());
Upvotes: 4