首页 > 解决方案 > 如何在 ASP.net Web API 中使用详细参数隐藏/显示结果 JSON

问题描述

我编写了一个 ASP.Net Web API,我要求根据参数显示完整/某些结果 JSON,即 verbose=true

解释这个要求。

我当前的 JSON 是

不冗长

获取方法:

api/v1/患者?键=1

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

用冗长的

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

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

我的用户.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;}       
}

基于详细参数,我将隐藏/显示 JSON 中的一些字段。

有什么办法可以做到这一点?

标签: c#jsonasp.net-web-api

解决方案


您可以使用继承

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;}       
}

并让端点根据提供的参数返回类型。

//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);
}

推荐阅读