0

Mine is a .net core web api which returns user details: I have a model class like this :

public class UserDetails
    {

        [JsonProperty("name")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [JsonProperty("lastName")]
        public string LastName { get; set; }

        [JsonProperty("designation")]
        public string Designation { get; set; }
    }

I have an method in Data base Layer which fetches some user details from Mongo and de-serializes the json and casts into UserDetails type.

When I see the response of the end point in postman , I see it like this :

> {
>             "name": "ABC",
>             "LastName": "XYZ",
>             "designation": "team Lead"
>         }

The Display Name which I mentioned as annotation on top of the property is not working.
How can I make my code return First Name instead of "name". Many thanks for all the answers.

CrazyCoder
  • 2,194
  • 10
  • 44
  • 91
  • The `DisplayName` attribute is used by UIs; JSON serialisation (from your API as well) will use the `JsonProperty` attributes, if present, or else just the property names. – sellotape May 12 '21 at 21:45

1 Answers1

1

DisplayAttribute doesn't work as you're expecting.

You're building a .NET Core Web Api, when the DisplayAttribute is only used in UI's - therefore .NET MVC projects.

In order to achieve what you want, there are a couple of possibilities:

  1. It looks like that your UserDetails model is currently handling a lot of responsibilities. As is, it's used to bind the data coming from MongoDB, it lives in your domain and represents the model sent to client side. So, in my opinion, you should create a DTO class (UserDetailsDTO). Then you just need to map the properties from your domain model to DTO. This gives you the flexibility of what you want to expose or not to client side.
public class UserDetailsDTO
{
    [JsonProperty("first name")]
    public string FirstName { get; set; }

    [JsonProperty("lastName")]
    public string LastName { get; set; }

    [JsonProperty("designation")]
    public string Designation { get; set; }
}
  1. If you don't like the first approach and if you're using Newtonsoft.Json (which I think you're based on the JsonPropertyAttribute), you could create a CustomContractResolver - as shown here https://stackoverflow.com/a/33290710/15749118.

If you're using System.Text.Json, I don't think Microsoft has this feature available. At least, I found a couple of open issues on GitHub asking for this.

Tiago Rios
  • 243
  • 2
  • 10