简体   繁体   中英

Display Name annotation on property in .net core web api

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM