c# - DateTime 的通用端点还是三个不同的端点?
问题描述
我有一个问题,因为我以前遇到过这种情况,我想知道最佳实践。
假设您想要这三个端点。
host:port/api/movies/published/2012
从 '2012' 返回所有,按发布日期(M13,M1)
host:port/api/movies/published/2012/8
排序 返回所有来自 '2012-08',按发布日期(M1)排序
host:port/api/movies/published/2012/8/15
返回所有来自 '2012-08-15',按发布日期(M1)排序
您是否会完成这样的通用端点,或者在这些情况下最佳实践是什么?你会怎么解决?
[HttpGet("published/{year:int}/{month:int?}/{day:int?}/")]
public void GetMoviesSortedByPublishedDateAsync(int year, int month = 0, int day = 0)
{
if (month == 0)
{
var date = new DateTime(year, 1, 1);
await _cosmosDbService.GetMoviesByYear(date.Year);
}
else if(day == 0)
{
var date = new DateTime(year, month, 1);
await _cosmosDbService.GetMoviesByYearAndMonth(date.Year, date.Month);
}
else
{
var date = new DateTime(year, month, day);
await _cosmosDbService.GetMoviesByPublishedDate(date);
}
}
解决方案
您所拥有的可能会起作用,但它确实有一些可能的缺点,包括将参数构建到 URL 路径中最终会创建无限数量的可能路径这一事实。如果您想分析或过滤您的流量日志或以其他方式进行额外的请求处理,解析这些路径组合可能会导致一些痛苦。
将日期作为查询字符串中的参数似乎是一种更好的做法,这对于 REST URL来说更惯用。它可以是ISO 8601 格式的日期前缀,它自然是可排序的。然后,您的查询可以利用 Cosmos DB 中的本机STARTSWITH来有效地过滤和排序publishedDate
属性。
它可能看起来像这样:
[HttpGet("{published}")]
public void GetMoviesSortedByPublishedDateAsync(string published)
{
if(!string.IsNullOrEmpty(published) // Validate better than this :)
{
// Queries container where published date STARTSWITH specified value
await _cosmosDbService.GetMoviesByPublishPrefix(published);
}
}
可能的值可以是任何有效的日期前缀,可选的 2 位数日/月:
2020 => GET https://app.com/movies?published=2020
2020-03 => GET https://app.com/movies?published=2020-03
2020-03-13 => GET https://app.com/movies?published=2020-03-01
推荐阅读
- visual-studio-code - VSCode 智能感知速度非常慢
- database - 添加列后如何将数据恢复到postgresql数据库?
- angular - Angular Universal/Prerendering 会加载动态加载的内容吗?
- javascript - 修复和取消修复超过 div 高度的滚动菜单
- android - 在 Android 上的 XML 布局文件中为 VideoView 设置 imageUrl
- html - 我尝试在 HTML 中使用图像,为什么不显示
- excel - 加载图像,并通过选择依赖组合框填充列表框
- java - Math.round(float a) vs. (int) 铸造性能
- sql-server - 创建存储过程并声明外键
- c# - 为什么当按下 L 键加载播放器旋转时它什么也没做?