0

Following api function returns PartnerApiModel object, which is good.

[HttpGet]
public HttpResponseMessage Get()
{
   PartnerAPIModel apiPartner = new PartnerAPIModel();
   apiPartner.PublicId = "1";
   apiPartner.DisplayName = "Show this";
   apiPartner.Name = "Test";

   return Request.CreateResponse(HttpStatusCode.OK, apiPartner);
}

The result:

{
    "PublicId": "7eda5b39-7ef8-ea29-6136-37701e05b0cc",
    "DisplayName": "Show this",
    "Name": "Test",
}

Is it possible to return only following?

{
    "PublicId": "7eda5b39-7ef8-ea29-6136-37701e05b0cc",
    "DisplayName": "Show this",
}
mrd
  • 2,095
  • 6
  • 23
  • 48
  • Yes, Show us `PartnerAPIModel ` model – Roman Marusyk Jun 25 '20 at 13:07
  • You can create another model/dto which will contain only needed fields. Or use `JsonSerializerOptions.IgnoreNullValues` or `NullValueHandling.Ignore`(depends in underlying json serializer) and don't set `Name`. Or mark property with corresponding `Ignore` attribute. Depends on concrete use-case. – Guru Stron Jun 25 '20 at 13:07
  • 1
    Remove the `Name` property from `PartnerAPIModel`? – David Jun 25 '20 at 13:07
  • 1
    Does this answer https://stackoverflow.com/questions/11851207/prevent-property-from-being-serialized-in-web-api – MBB Jun 25 '20 at 13:10
  • Does this answer your question? [prevent property from being serialized in web API](https://stackoverflow.com/questions/11851207/prevent-property-from-being-serialized-in-web-api) – Crowcoder Jun 25 '20 at 13:21
  • Why set the `Name` if you don't want it returned? – mjwills Jun 25 '20 at 13:35

1 Answers1

0

Mark the propertie who you want to ignore with jsonIgnore:

using Newtonsoft.Json;
public class PartnerApiModel {
    [JsonIgnore]
    public string Name {get; set;}
}
Paulo
  • 577
  • 3
  • 8
  • 23