private ResourceCollect <BookDto> CreateLinksForBooks(Guid authorId, ResourceCollect <BookDto> books) { books.Links.Clear(); books.Links.Add(new Link(HttpMethods.Get.ToString(), "self", Url.Link(nameof(GetBookAsync), new { authorId }))); books.Links.Add(new Link(HttpMethods.Delete.ToString(), "create book", Url.Link(nameof(CreateBookAsync), null))); return(books); }
public async Task Tets_GetAllAuthors() { // Arrange var author = new Author { Id = Guid.NewGuid(), Name = "Author Test 1", Email = "*****@*****.**", BirthPlace = "Beijing" }; var authorDto = new AuthorDto { Id = author.Id, Name = author.Name, Email = author.Email, BirthPlace = author.BirthPlace }; var authorList = new List <Author> { author }; var authorDtoList = new List <AuthorDto> { authorDto }; var parameters = new AuthorResourceParameters(); var authors = new PagedList <Author>(authorList, totalCount: authorList.Count, pageNumber: parameters.PageNumber, pageSize: parameters.PageSize); _mockAuthorRepository.Setup(m => m.GetAllAsync(It.IsAny <AuthorResourceParameters>())).Returns(Task.FromResult(authors)); _mockMapper.Setup(m => m.Map <IEnumerable <AuthorDto> >(It.IsAny <IEnumerable <Author> >())).Returns(authorDtoList); _mockUrlHelper.Setup(m => m.Link(It.IsAny <string>(), It.IsAny <object>())).Returns("demo url"); _authorController.Url = _mockUrlHelper.Object; // Act var actionResult = await _authorController.GetAuthorsAsync(parameters); // Assert ResourceCollect <AuthorDto> resourceCollect = actionResult.Value; Assert.True(1 == resourceCollect.Items.Count); Assert.Equal(authorDto, resourceCollect.Items[0]); Assert.True(_authorController.Response.Headers.ContainsKey("X-Pagination")); }
public async Task <ActionResult <ResourceCollect <BookDto> > > GetBooksAsync([FromRoute] Guid authorId) { string key = $"{authorId}_books"; if (!MemoryCache.TryGetValue(key, out ResourceCollect <BookDto> resourceList)) { var books = await RepositoryWrapper.Book.GetBooksAsync(authorId); if (books == null || !books.Any()) { return(NotFound()); } var bookDtoList = Mapper.Map <IEnumerable <BookDto> >(books).ToList(); bookDtoList = bookDtoList.Select(book => CreateLinkForBook(authorId, book)).ToList(); resourceList = new ResourceCollect <BookDto>(bookDtoList); //MemoryCache.Set(key, bookDtoList); #pragma warning disable CS1587 // XML 注释没有放在有效语言元素上 /** * 使用MemoryCacheEntryOptions对象可控制缓存时间和优先级等属性 * 1>. 合理使用有效时间,不仅能确保资源被及时更新,也能使当资源不再使用时,所占用的内存能自动恢复 * 2>. 使用优先级属性,决定了当服务器内存不足时是否先将该项移除,当优先级为低时,将会被先移除。 * 如果不希望缓存项被移除,则应设置Priority属性为CacheItemPriority.NeverRemove。 */ #pragma warning restore CS1587 // XML 注释没有放在有效语言元素上 MemoryCacheEntryOptions options = new MemoryCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddMinutes(10), // 有效时间为10分钟 Priority = CacheItemPriority.Normal // 优先级为默认 }; MemoryCache.Set(key, resourceList, options); } return(resourceList); }