Skip to main content
 首页 » 编程设计

c#之如何在 ASP.net Web API 中使用详细参数隐藏/显示结果 JSON

2024年02月04日36bluestorm

我已经编写了一个 ASP.Net Web API,我需要根据参数即 verbose=true 显示完整/部分结果 JSON>

解释这个要求。

我当前的 JSON 是

不冗长

获取方法:

api/v1/patient?Key=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": "" 
        } 
} 

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

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

有什么办法可以实现吗?

请您参考如下方法:

可以使用继承

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