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



我编写了一个 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/患者?键=1&详细=真

{
"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 中的一些字段。

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

您可以使用继承

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

最新更新