c# - 如何在 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 中的一些字段。
有什么办法可以做到这一点?
解决方案
您可以使用继承
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);
}
推荐阅读
- python - 使用libtiff库时如何防止python中的最大递归运行时错误
- php - 添加属性选择表单 Symfony
- crafter-cms - Craftercms - 社交:是否可以指定“创建评论”API 应该检索哪些用户属性?
- nginx - 使用 nginx 到不同主机的不同前缀路径
- excel - 使用 VBA 绕过网站的安全证书警告
- android - 迁移到 androidX 后,Retrofit 界面中的 Kapt NonExistentClass 异常
- javascript - fancybox 两个图像显示在同一个窗口
- python - 带有“+”选项的 argparse
- javascript - 用另一个 HTML 标记将 HTML 标记包装在纯字符串中
- javascript - React Native 未处理的异常未在 ErrorUtils 中捕获 & 发布 APK 显示空白屏幕而不是在 JS 异常上崩溃