3

I want to hide Modifiedby, Modifieddate and Createddate properties from web api response.

I tried using [JsonOgnore], [IgnoreDataMember] but non worked.

[ModelMetadataType(typeof(UserModel))]
partial class TUsers
{
}

public class UserModel
{
    public int Userid { get; set; }
    [Required]
    public string Firstname { get; set; }
    public string Middlename { get; set; }
    public string Lastname { get; set; }
    public int? Modifiedby { get; set; }
    public DateTime? Modifieddate { get; set; }
    public DateTime? Createddate { get; set; }
}


    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        try
        {
            var user = _service.GetUser(id);
            return Ok(new { status = Constants.Success, message = "", User = user });
        }
        catch (Exception ex)
        {
            return BadRequest(new { status = Constants.Failed, message = ex.Message });
        }
    }

Actual Result

{
    "status": "success",
    "message": "",
    "user": {
        "userid": 0,
        "firstname": null,
        "middlename": null,
        "lastname": null,
        "modifiedby": null,
        "modifieddate": null,
        "createddate": null
    }
}

Expected Result

{
    "status": "success",
    "message": "",
    "user": {
        "userid": 0,
        "firstname": null,
        "middlename": null,
        "lastname": null
    }
}
Matthijs
  • 2,483
  • 5
  • 22
  • 33
Naveen
  • 41
  • 1
  • 4
  • 2
    It's `[JsonIgnore]` not `[JsonOgnore]` (is it a typo?), and should works – ALFA Apr 23 '19 at 06:45
  • 1
    `[JsonIgnore]` will work if you are returning that class in your Web Api Response. It might be useful to see how you are also returning the data? – Jamie Rees Apr 23 '19 at 07:21
  • create separate Data Transfer Objects (DTOs) containing only properties you want to expose to your client and map your models to DTOs when sending back response. – dee zg Apr 23 '19 at 07:26
  • If you class UserModel is something that reflects DB entity, I usually use another class (e.g. UserViewModel) to return from WebApi, and then I populate just required properties – JavierFromMadrid Apr 23 '19 at 07:29
  • Does this answer your question? [How can we hide a property in WebAPI?](https://stackoverflow.com/questions/30610399/how-can-we-hide-a-property-in-webapi) – Damjan Pavlica Nov 17 '21 at 18:11

2 Answers2

10

Simply, You can use the below attribute.

[JsonIgnore]
public int? Modifiedby { get; set; }
SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32
2

You've mentioned using [JsonOgnore] it should be [JsonIgnore] on the properties you want to exclude, this should work.

However instead of passing User object you can create UserModel that has exactly the properties you need and then pass UserModel object to the Response, but here you need to map the properties from User to UserModel but'll be more readable than excluding properties from being serialized.

Anas AL-zghoul
  • 465
  • 5
  • 14