简体   繁体   中英

How to hide/show the result JSON using verbose parameter in ASP.net Web API

I've written an ASP.Net web API, my requirement to show the full/some result (s) JSON based on the parameter ie, verbose=true

To Explain this requirements.

My current JSON is

Without verbose

GET Method:

api/v1/patient?Key=1

{
    "user": {           
            "key": 1,
            "suffix": "1",
            "firstName": "Dhanu",
            "lastName": "Kumar",
            "middleName": "",
            "address": {
                "address1": "uuu",
                "address2": "TTT",
                "address3": "xx",
                "city": "yy"           
            }
        }
}

With verbose

api/v1/patient?Key=1&verbose=true

{
    "user": {           
            "key": 1,
            "firstName": "Dhanu",
            "lastName": "Kumar",
            "middleName": ""
        }
}

My User.cs

public UserDTO()
{
    public int Key { get; set; }
    public string Suffix { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public Address Address {get;set;}       
}

Based on the verbose parameter, I'll Hide/Show some fields from the JSON.

Is there any way to achieve this?

You can use inheritance

public class UserDTO {
    public int Key { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }    
}

public class VerboseUserDTO: UserDTO {
    public string Suffix { get; set; }
    public Address Address {get;set;}       
}

and have the endpoint return the type based on provided parameter.

//api/v1/patient
public IHttpActionResult Get(int key, bool verbose = false) {
    //...get data based on key

    if(data == nul)
        return NotFound();

    if(verbose) {
        var verboseDto = new { 
            user = new VerboseUserDTO {
                //...populated from data
            }
        };
        return Ok(verboseDto);
    }

    var dto = new { 
        user =  new UserDTO {
            //...populated from data    
        }
    };    
    return Ok(dto);
}

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