这个逻辑和分页查询文章列表是差不多的,联合查询文章表和分类表,关联字段为CategoryId,指定查询条件categories.DisplayName==name,以CreationTime倒序排序,年份分组,筛选出所需字段返回,在BlogController中添加API。
/// <summary> /// 通过分类名称查询文章列表 /// </summary> /// <param></param> /// <returns></returns> [HttpGet] [Route("posts/category")] public async Task<ServiceResult<IEnumerable<QueryPostDto>>> QueryPostsByCategoryAsync([Required] string name) { return await _blogService.QueryPostsByCategoryAsync(name); } 标签名称&文章列表分析:此页面和分类页一样,包含两个接口,查询标签的名称和当前标签下的文章列表。
标签名称添加获取标签名称接口和缓存接口,GetTagAsync()。
//IBlogService.Tag.cs /// <summary> /// 获取标签名称 /// </summary> /// <param></param> /// <returns></returns> Task<ServiceResult<string>> GetTagAsync(string name); //IBlogCacheService.Tag.cs /// <summary> /// 获取标签名称 /// </summary> /// <param></param> /// <param></param> /// <returns></returns> Task<ServiceResult<string>> GetTagAsync(string name, Func<Task<ServiceResult<string>>> factory);实现这两个接口。
//BlogCacheService.Tag.cs ... public partial class BlogCacheService { private const string KEY_GetTag = "Blog:Tag:GetTag-{0}"; /// <summary> /// 获取标签名称 /// </summary> /// <param></param> /// <param></param> /// <returns></returns> public async Task<ServiceResult<string>> GetTagAsync(string name, Func<Task<ServiceResult<string>>> factory) { return await Cache.GetOrAddAsync(KEY_GetTag.FormatWith(name), factory, CacheStrategy.ONE_DAY); } } ... //BlogService.Tag.cs /// <summary> /// 获取标签名称 /// </summary> /// <param></param> /// <returns></returns> public async Task<ServiceResult<string>> GetTagAsync(string name) { return await _blogCacheService.GetTagAsync(name, async () => { var result = new ServiceResult<string>(); var tag = await _tagRepository.FindAsync(x => x.DisplayName.Equals(name)); if (null == tag) { result.IsFailed(ResponseText.WHAT_NOT_EXIST.FormatWith("标签", name)); return result; } result.IsSuccess(tag.TagName); return result; }); }FormatWith()是扩展方法,ResponseText.WHAT_NOT_EXIST是之前说过的常量,直接查询是否存在当前name的分类,如果不存在给出错误提示,存在的话,则只返回分类名称,在BlogController中添加API。
/// <summary> /// 获取标签名称 /// </summary> /// <param></param> /// <returns></returns> [HttpGet] [Route("tag")] public async Task<ServiceResult<string>> GetTagAsync(string name) { return await _blogService.GetTagAsync(name); }[Required]Attribute 指定参数name必填。
文章列表和上面一模一样的,添加通过标签名称查询文章列表接口和缓存接口。
//IBlogService.Post.cs /// <summary> /// 通过标签名称查询文章列表 /// </summary> /// <param></param> /// <returns></returns> Task<ServiceResult<IEnumerable<QueryPostDto>>> QueryPostsByTagAsync(string name); //IBlogCacheService.Post.cs /// <summary> /// 通过标签名称查询文章列表 /// </summary> /// <param></param> /// <param></param> /// <returns></returns> Task<ServiceResult<IEnumerable<QueryPostDto>>> QueryPostsByTagAsync(string name, Func<Task<ServiceResult<IEnumerable<QueryPostDto>>>> factory);