Exemple #1
0
        public async Task <IActionResult> GetHateoas(PostParameters postParameters)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                return(BadRequest("Can't finds fields for sorting."));
            }

            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                return(BadRequest("Fields not exist."));
            }
            var postList = await _postRepository.GetAllPostsAsync(postParameters);

            var postResource       = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);
            var shapedPostResource = postResource.ToDynamicIEnumerable(postParameters.Fields);
            var proviousPage       = postList.HasPrevious ? CreatePostUri(postParameters, PaginationResourceUriType.PreviousPage) : null;
            var nextPage           = postList.HasNext ? CreatePostUri(postParameters, PaginationResourceUriType.NextPage) : null;
            var meta = new
            {
                PageIndex       = postList.PageIndex,
                PageSize        = postList.PageSize,
                TotalItemsCount = postList.TotalItemsCount,
                PageCount       = postList.Count,
                proviousPage,
                nextPage
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));
            return(Ok(shapedPostResource));
        }
Exemple #2
0
        public async Task <IActionResult> GetHateoas(PostParameters parameters)
        {
            //验证排序属性映射是否存在
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostDTO, Post>(parameters.OrderBy))
            {
                return(BadRequest("Can't finds fields for sorting."));
            }

            //验证Filed是否存在
            if (!_typeHelperService.TypeHasProperties <PostDTO>(parameters.Fields))
            {
                return(BadRequest("Filed not exits"));
            }


            var posts = await _postRepository.GetPostsAsync(parameters);

            var postDto = _mapper.Map <IEnumerable <Post>, IEnumerable <PostDTO> >(posts);

            var shapePostDTO     = postDto.ToDynamicIEnumerable(parameters.Fields);
            var previousPageLink = posts.HasPrevious ?
                                   CreatePostUri(parameters, PaginationResourceUriType.PreviousPage) : null;

            var nextPageLink = posts.HasNext ?
                               CreatePostUri(parameters, PaginationResourceUriType.NextPage) : null;


            var shapedWithLinks = shapePostDTO.Select(x =>
            {
                var dict      = x as IDictionary <string, object>;
                var postLinks = CreateLinksForPost((int)dict["Id"], parameters.Fields);
                dict.Add("links", postLinks);
                return(dict);
            });
            var links  = CreateLinksForPosts(parameters, posts.HasPrevious, posts.HasNext);
            var result = new
            {
                value = shapedWithLinks,
                links
            };


            var meta = new
            {
                PageSize       = posts.PageSize,
                PageIndex      = posts.PageIndex,
                TotalItemCount = posts.TotalItemsCount,
                PageCount      = posts.PageCount,
                previousPageLink,
                nextPageLink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            return(Ok(result));
        }
Exemple #3
0
        public async Task <IActionResult> GetHateoas(PostParameters postParameters)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                return(BadRequest("Can't finds fields for sorting."));
            }

            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                return(BadRequest("Fields not exist."));
            }

            var postList = await _postRepository.GetAllPostsAsync(postParameters);

            var postResources = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);

            // 资源塑形
            var shapedPostResources = postResources.ToDynamicIEnumerable(postParameters.Fields);

            var shapedWithLinks = shapedPostResources.Select(x =>
            {
                var dict      = x as IDictionary <string, object>;
                var postlinks = CreateLinksForPost((int)dict["Id"], postParameters.Fields);
                dict.Add("links", postlinks);
                return(dict);
            });

            var links = CreateLinksForPosts(postParameters, postList.HasPrevious, postList.HasNext);

            var result = new
            {
                value = shapedWithLinks,
                links
            };

            var meta = new
            {
                postList.PageSize,
                postList.PageIndex,
                postList.TotalItemsCount,
                postList.PageCount,
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            return(Ok(result));
        }
Exemple #4
0
        public async Task <IActionResult> GetDictionaries([FromQuery] DictionariesParameters parameters)
        {
            try
            {
                //验证排序的字段是否存在
                if (!propertyMappingContainer.ValidateMappingExistsFor <DictionariesViewModel, Dictionaries>(parameters.OrderBy))
                {
                    return(BadRequest("order by Fidled not exist"));
                }

                //验证过滤的字段是否存在
                if (!typeHelperService.TypeHasProperties <DictionariesViewModel>(parameters.Fields))
                {
                    return(BadRequest("fidled not exist"));
                }

                var users = await repository.GetAllDicAsync(parameters);

                var userViewModel = mapper.Map <IEnumerable <Dictionaries>, IEnumerable <DictionariesViewModel> >(users);
                return(Ok(new BaseResponse()
                {
                    success = true, dynamicObj = userViewModel, TotalRecord = users.TotalItemsCount
                }));
            }
            catch (Exception ex)
            {
                return(Ok(new BaseResponse()
                {
                    success = false, message = ex.Message
                }));
            }
        }
        public async Task <IActionResult> Get(PostParameter postParameter)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostModel, Post>(postParameter.OrderBy))
            {
                return(BadRequest("can't find fields for sorting"));
            }
            if (!_typeHelperService.TypeHasProperties <PostModel>(postParameter.Fields))
            {
                return(BadRequest("Fields not exits"));
            }
            var posts = await _postBusiness.RetriveAllEntity(postParameter);

            var postModels       = _mapper.Map <IEnumerable <Post>, IEnumerable <PostModel> >(posts);
            var postsResult      = postModels.ToDynamicIEnumerable(postParameter.Fields);
            var previousPageLink = posts.HasPrevious ?
                                   CreatePostUri(postParameter, PaginationResourceUriType.PreviousPage) : null;

            var nextPageLink = posts.HasNext ?
                               CreatePostUri(postParameter, PaginationResourceUriType.NextPage) : null;
            var meta = new
            {
                posts.PageSize,
                posts.PageIndex,
                posts.TotalItemsCount,
                posts.PageCount,
                previousPageLink,
                nextPageLink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
            }));
            return(Ok(postsResult));
        }
 /// <summary>
 /// 判断相应的字段是否能排序
 /// </summary>
 /// <param name="orderBy"></param>
 /// <returns></returns>
 protected void ValidateMapping <TResource, TEntity>(string orderBy) where TEntity : IEntity
 {
     if (!_propertyMappingContainer.ValidateMappingExistsFor <TResource, TEntity>(orderBy))
     {
         Results.Add(BadRequest(new BadRequestForSortingMessage()));
     }
 }
        public async Task <IActionResult> Get(PostParameters postParameters)
        {
            //检查按照某个字段排序时该字段是否存在
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                return(BadRequest("OrderBy is not exist"));
            }
            //检查资源塑性字段是否存在
            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                return(BadRequest("Fields is not exist"));
            }
            var postList = await _postRepository.GetAllPostsAsync(postParameters);

            //转化实体
            var postResources = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> > (postList);

            //资源塑性
            var shapedPostResources = postResources.ToDynamicIEnumerable(postParameters.Fields);

            //前一页
            var previousPageLink = postList.HasPrevious ?
                                   CreatePostUri(postParameters,
                                                 PaginationResourceUriType.PreviousPage) : null;
            //后一页
            var nextPageLink = postList.HasNext ?
                               CreatePostUri(postParameters,
                                             PaginationResourceUriType.NextPage) : null;

            var meta = new
            {
                PageSize        = postList.PageSize,
                PageIndex       = postList.PageIndex,
                TotalItemsCount = postList.TotalItemsCount,
                PageCount       = postList.PageCount,
                previousPageLink,
                nextPageLink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver() //转化数据不管大小写,首字母都转化为小写
            }));


            return(Ok(shapedPostResources));
        }
        [RequestHeaderMatchingMediaType("Accept", new[] { "application/json" })] //新增媒体类型参数,在Header里是叫做Accept的key
        public async Task <IActionResult> Get(PostParameters postParameters)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                //如果需要查询排序的字段不存在,则返回400错误
                return(BadRequest("Can't finds fields for sorting"));
            }

            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                //如果需要查询的字段不存在,则返回400错误
                return(BadRequest("Fields not exist."));
            }

            var postList = await _postRepository.GetAllPostsAsync(postParameters);

            //var a =postList.FirstOrDefault();
            var postResource = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);
            //如果Headers里面有注明输出的媒体类型为application/vnd.cgzl.hateoas+json 则走下面,带links的

            var previousPageLink = postList.HasPrevious ?
                                   CreatePostUri(postParameters,
                                                 PaginationResourceUriType.PreviousPage) : null;

            var nextPageLink = postList.HasNext ?
                               CreatePostUri(postParameters,
                                             PaginationResourceUriType.NextPage) : null;

            var meta = new
            {
                postList.TotalItemsCount,
                postList.PageSize,
                postList.PageIndex,
                postList.PageCount,
                previousPageLink,
                nextPageLink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            return(Ok(postResource.ToDynamicIEnumerable(postParameters.Fields)));
        }
        /// <summary>
        /// 判断相应的字段是否能排序
        /// </summary>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        protected void ValidateMapping(string orderBy)
        {
            //MethodInfo mi = _propertyMappingContainer.GetType()
            //    .GetMethod(nameof(_propertyMappingContainer.ValidateMappingExistsFor));
            //var valueInvoke = mi.MakeGenericMethod(new Type[] {ResourceType, EntityType})
            //    .Invoke(_propertyMappingContainer, new object[] {orderBy});

            //if (!(bool) valueInvoke)
            //{
            //    Results.Add(BadRequest(new BadRequestForSortingMessage()));
            //}

            if (!_propertyMappingContainer.ValidateMappingExistsFor <TResource, TEntity>(orderBy))
            {
                Results.Add(BadRequest(new BadRequestForSortingMessage()));
            }
        }
        protected async Task <PaginatedList <TResource> > GetListByPagingParamAsync <TResource, TEntity, TPrimaryKey>
            (IRepositoryHasPaging <TEntity, TPrimaryKey> repository, PagingParam param)
            where TResource : class
            where TEntity : class, IEntity <TPrimaryKey>
        {
            if (!_pmContainer.ValidateMappingExistsFor <TResource, TEntity, TPrimaryKey>(param.OrderBy))
            {
                throw new FriendlyException("无法找到用于排序的字段!");
            }

            var data = await repository
                       .GetListByPagingParameterAsync <TResource>(param);

            var resoures = _mapper.Map <IEnumerable <TResource> >(data);

            return(new PaginatedList <TResource>(
                       data.PageIndex, data.PageSize, data.TotalItemsCount, resoures));
        }
Exemple #11
0
        public async Task <ActionResult> Get(PostParameters parameters)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(parameters.OrderBy))
            {
                return(BadRequest("OrderBy not exist "));
            }

            if (!_typeHelperService.TypeHasProperties <PostResource>(parameters.Fields))
            {
                return(BadRequest("fields not exist "));
            }

            var postsList = await _postRepository.GetAllPostsAsync(parameters);

            //  _logger.LogError(12,"get post all/.....");
            var resources = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postsList);

            //动态查询字段
            var result = resources.ToDynamicIEnumerable(parameters.Fields);

            //创建上一页
            var previousPagelink = postsList.HasPrevious ? CreatePostUri(parameters, PaginationResourceUriType.PreviousPage) : null;
            //创建下一页
            var nextPagelink = postsList.HasNext ? CreatePostUri(parameters, PaginationResourceUriType.NextPage) : null;


            var meta = new
            {
                postsList.PageSize,
                postsList.PageIndex,
                postsList.TotalItemCount,
                postsList.PageCount,
                previousPagelink,
                nextPagelink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                //大写转小写
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));
            return(Ok(result));
        }
Exemple #12
0
        public async Task <IActionResult> Get(PostParameters postParameters, [FromHeader(Name = "Accept")] string mediaType)
        {
            //验证排序属性
            if (!_propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postParameters.OrderBy))
            {
                return(BadRequest("Cann't finds for sorting."));
            }
            //验证塑形字段
            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                return(BadRequest("Fields not exist"));
            }

            var postList = await _postRepository.GetPostsAsync(postParameters);

            var postResources = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postList);

            if (mediaType == "application/vnd.cgzl.hateoas+json")
            {
                //塑形
                var shapedPostResources = postResources.ToDynamicIEnumerable(postParameters.Fields);

                var shapedWithLinks = shapedPostResources.Select(
                    p =>
                {
                    var dict      = p as IDictionary <string, object>;
                    var postLinks = CreateLinksForPost((int)dict["Id"], postParameters.Fields);
                    dict.Add("links", postLinks);
                    return(dict);
                });

                var links = CreateLinksForPosts(postParameters, postList.HasPrevious, postList.HasNext);

                var result = new
                {
                    value = shapedWithLinks,
                    links
                };


                //生成上一页下一页的链接
                //var previousPageLink = postList.HasPrevious ?
                //    CreatePostUri(postParameters, PaginationResourceUriType.PreviousPage) : null;
                //var nextPageLink = postList.HasNext ?
                //    CreatePostUri(postParameters, PaginationResourceUriType.NextPage) : null;

                var meta = new
                {
                    PageIndex       = postList.PageIndex,
                    PageSize        = postList.PageSize,
                    TotalItemsCount = postList.TotalItemsCount,
                    PageCount       = postList.PageCount,
                    //属性名不写,默认和值名字相同
                    //previousPageLink,
                    //nextPageLink
                };
                //将分页的 元数据 从自定义的Headers里面返回去
                Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
                {
                    //格式化对象的过程中,对象属性转换为“驼峰式”,即将 meta对象转换为json字符串的时候,首字母转为小写
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }));
                return(Ok(result));
            }
            else
            {
                var previousPageLink = postList.HasPrevious ?
                                       CreatePostUri(postParameters, PaginationResourceUriType.PreviousPage) : null;
                var nextPageLink = postList.HasNext ?
                                   CreatePostUri(postParameters, PaginationResourceUriType.NextPage) : null;

                var meta = new
                {
                    postList.TotalItemsCount,
                    postList.PageSize,
                    postList.PageIndex,
                    postList.PageCount,
                    previousPageLink,
                    nextPageLink
                };

                Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }));

                var responseData = postResources.ToDynamicIEnumerable(postParameters.Fields);
                return(Ok(responseData));
            }
        }
        public async Task <IActionResult> GetPostsHateoas(PostQueryParameters postQueryParameters)
        {
            #region 参数合法性判断
            //排序字段合法性判断
            if (!string.IsNullOrWhiteSpace(postQueryParameters.OrderBy) &&
                !propertyMappingContainer.ValidateMappingExistsFor <PostResource, Post>(postQueryParameters.OrderBy))
            {
                return(BadRequest("排序属性映射关系不存在,或不可通过该排序属性排序"));
            }
            //塑形字段合法性判断
            if (!string.IsNullOrWhiteSpace(postQueryParameters.Fields) &&
                !typeHelperService.TypeHasProperties <PostResource>(postQueryParameters.Fields))
            {
                return(BadRequest("传入的塑形属性不合法"));
            }
            #endregion

            //返回带有元数据的PaginatedList数据
            var postsWithMateData = await postRepository.GetAllPostsAsync(postQueryParameters);

            //将posts集合映射为PostResource集合,取出其中的post数据集合
            var postResources = mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(postsWithMateData);
            //针对ResourceModel进行属性塑形
            var shapedPostResources = postResources.ToDynamicIEnumerable(postQueryParameters.Fields);

            #region 针对每个postResource添加HATEOAS的LINKS属性
            var shapedWithLinks = shapedPostResources.Select(x =>
            {
                var dict      = x as IDictionary <string, object>;
                var postLinks = CreateLinksForPost((int)dict["id"], postQueryParameters.Fields);
                dict.Add("links", postLinks);
                return(dict);
            });
            #endregion

            #region 针对整个postsResource添加HATEOAS的Links属性
            var links = CreateLinksForPosts(postQueryParameters, postsWithMateData.HasPrevious, postsWithMateData.HasNext);

            var result = new
            {
                values = shapedWithLinks,
                links
            };
            #endregion


            #region 提取元数据,并将该数据添加到响应Response自定义X-Pagination的Header中
            //提取元数据
            var mate = new
            {
                postsWithMateData.PageSize,
                postsWithMateData.PageIndex,
                postsWithMateData.TotalItemsCount,
                postsWithMateData.PageCount
            };


            //将翻页元数据添加到响应Header的X-Pagination中
            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(mate, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver() //将所有mate元数据属性首字母小写返回
            }));
            #endregion

            //logger.LogError("测试的错误日志记录");
            //throw new Exception("发生了错误");
            return(Ok(result));
        }
Exemple #14
0
        public async Task <IActionResult> GetProducts(ProductResourceParameters productResourceParameters,
                                                      [FromHeader(Name = "Accept")] string mediaType)
        {
            if (!_propertyMappingContainer.ValidateMappingExistsFor <ProductResource, Product>(productResourceParameters.OrderBy))
            {
                return(BadRequest("Can't find the fields for sorting."));
            }

            if (!_typeHelperService.TypeHasProperties <ProductResource>(productResourceParameters.Fields))
            {
                return(BadRequest("Can't find the fields on Resource."));
            }

            var pagedList = await _productRepository.GetProductsAsync(productResourceParameters);

            var productResources = _mapper.Map <List <ProductResource> >(pagedList);

            if (mediaType == "application/vnd.solenovex.hateoas+json")
            {
                var meta = new
                {
                    pagedList.TotalItemsCount,
                    pagedList.PaginationBase.PageSize,
                    pagedList.PaginationBase.PageIndex,
                    pagedList.PageCount
                };

                Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }));

                var links                    = CreateLinksForProducts(productResourceParameters, pagedList.HasPrevious, pagedList.HasNext);
                var shapedResources          = productResources.ToDynamicIEnumerable(productResourceParameters.Fields);
                var shapedResourcesWithLinks = shapedResources.Select(product =>
                {
                    var productDict  = product as IDictionary <string, object>;
                    var productLinks = CreateLinksForProduct((int)productDict["Id"], productResourceParameters.Fields);
                    productDict.Add("links", productLinks);
                    return(productDict);
                });
                var linkedProducts = new
                {
                    value = shapedResourcesWithLinks,
                    links
                };

                return(Ok(linkedProducts));
            }
            else
            {
                var previousPageLink = pagedList.HasPrevious ?
                                       CreateProductUri(productResourceParameters,
                                                        PaginationResourceUriType.PreviousPage) : null;

                var nextPageLink = pagedList.HasNext ?
                                   CreateProductUri(productResourceParameters,
                                                    PaginationResourceUriType.NextPage) : null;

                var meta = new
                {
                    pagedList.TotalItemsCount,
                    pagedList.PaginationBase.PageSize,
                    pagedList.PaginationBase.PageIndex,
                    pagedList.PageCount,
                    previousPageLink,
                    nextPageLink
                };

                Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }));

                return(Ok(productResources.ToDynamicIEnumerable(productResourceParameters.Fields)));
            }
        }
        //https://localhost:5001/api/posts?pageIndex=3&pageSize=3

        public async Task <IActionResult> Get(PostParameters postParameters,
                                              [FromHeader(Name = "Accept")] string mediaType)
        {
            //排序字段验证 https://localhost:5001/api/posts?pageIndex=0&pageSize=10&orderBy=id,title&fields=id,count
            if (!_propertyMappingContainer.ValidateMappingExistsFor <BlogDemo.Infrastructure.Resources.PostResource, Post>(postParameters.OrderBy))
            {
                return(BadRequest("Can't finds fields for sorting."));
            }
            //写入字段的验证
            if (!_typeHelperService.TypeHasProperties <PostResource>(postParameters.Fields))
            {
                return(BadRequest("Fields not  exits"));
            }

            //var posts = await _myContext.Posts.ToListAsync();
            var posts = await _postRepository.GetAllPostsAsync(postParameters);

            //映射
            var postresource = _mapper.Map <IEnumerable <Post>, IEnumerable <PostResource> >(posts);

            //https://localhost:5001/api/posts?pageIndex=0&pageSize=10&orderBy=id&filed=id,title

            if (mediaType == "application/vnd.cgzl.hateoas+json")
            {
                var shapedPostResources = postresource.ToDynamicIEnumerable(postParameters.Fields);

                var shapedWithLinks = shapedPostResources.Select(x =>
                {
                    var dict      = x as IDictionary <string, object>;
                    var postLinks = CreateLinksForPost((int)dict["Id"], postParameters.Fields);
                    dict.Add("links", postLinks);
                    return(dict);
                });


                var links      = CreateLinksForPosts(postParameters, posts.HasPrevious, posts.HasNext);
                var resultlink = new
                {
                    value = shapedWithLinks,
                    links
                };

                #region  去掉放到了result里面

                //var previousPageLink = posts.HasPrevious ?
                //    CreatePostUri(postParameters,
                //        PaginationResourceUriType.PreviousPage) : null;
                //var nextPageLink = posts.HasNext ?
                //    CreatePostUri(postParameters,
                //        PaginationResourceUriType.NextPage) : null


                #endregion

                var meta = new
                {
                    posts.PageSize,
                    posts.PageIndex,
                    posts.TotalItemsCount,
                    posts.PageCount,
                    posts.Count
                };
                Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
                {
                    //改成属性名小写
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }));

                _logger.LogInformation(_configuration["key"]);
                _logger.LogInformation("Get All Post...");
                //return Ok(postresource);
                // return Ok(shapedPostResources);
                return(Ok(resultlink));
            }

            else
            {
                var previousPageLink = posts.HasPrevious ?
                                       CreatePostUri(postParameters,
                                                     PaginationResourceUriType.PreviousPage) : null;
                var nextPageLink = posts.HasNext
                    ? CreatePostUri(postParameters,
                                    PaginationResourceUriType.NextPage)
                    : null;
                var meta = new
                {
                    posts.PageSize,
                    posts.PageIndex,
                    posts.TotalItemsCount,
                    posts.PageCount,
                    previousPageLink,
                    nextPageLink,
                    posts.Count
                };

                //这部分相当于把要的参数加入到标头了,显示相关的信息 posts.TotalItemsCount总数,posts.Count当前页面数 重要

                Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
                {
                    //改成属性名小写
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }));
                return(Ok(postresource.ToDynamicIEnumerable(postParameters.Fields)));
            }
        }
        public async Task <IActionResult> Get([FromQuery] PostParameters postParameters)
        {
            //throw new Exception("Error!!");
            //var v = configuration["key1"];
            //logger.LogError("Get ALl Post...");

            PaginatedList <Post> postList = null;


            //string dbKey = $"api/Post?title={postParameters.Title}&pageIndex={postParameters.PageIndex}&pageSize={postParameters.PageSize}&orderBy={postParameters.OrderBy}&fields={postParameters.Fields}";
            //Newtonsoft.Json.JsonSerializer jsonSerializer = new Newtonsoft.Json.JsonSerializer();
            //if (db.KeyExists(dbKey))
            //{
            //    var resStr = db.StringGet(dbKey);
            //    var resStrEncoding = Encoding.UTF8.GetString(resStr);
            //    var res = JsonConvert.DeserializeObject<PaginatedList<Post>>(resStr);
            //}
            //else
            //{
            if (!typeHelperService.TypeHasProperties <PostDTO>(postParameters.Fields))
            {
                return(BadRequest("Fields not exists"));   //400错误
            }
            if (!propertyMappingContainer.ValidateMappingExistsFor <PostDTO, Post>(postParameters.OrderBy))
            {
                return(BadRequest("Fields not exists"));
            }
            postList = await postRepository.GetAllPostsAsync(postParameters);

            //    var objStr = JsonConvert.SerializeObject(postList);
            //    byte[] bytes = Encoding.UTF8.GetBytes(objStr);
            //    db.StringSet(dbKey, bytes, TimeSpan.FromMinutes(5));
            //}


            var postDTO = mapper.Map <IEnumerable <Post>, IEnumerable <PostDTO> >(postList);

            var result = postDTO.ToDynamicIEnumerable(postParameters.Fields);

            var shapeWithLinks = result.Select(x =>
            {
                var dict      = x as IDictionary <string, object>;
                var dictlinks = CreateLinksForPost((int)dict["Id"], postParameters.Fields);
                dict.Add("links", dictlinks);
                return(dict);
            });

            var links = CreateLinksForPosts(postParameters, postList.HasPrevious, postList.HasNext);

            var count = await postRepository.GetCount();

            var resultAll = new
            {
                value = shapeWithLinks,
                links,
                count = count
            };

            //var previousPageLink = postList.HasPrevious ?
            //    CreatePostUri(postParameters, PaginationResourceUriType.PreviousPage) : null;
            //var nextPageLink = postList.HasNext ?
            //     CreatePostUri(postParameters, PaginationResourceUriType.NextPage) : null;

            var meta = new
            {
                Pagesize        = postList.PageSize,
                PageIndex       = postList.PageIndex,
                TotalItemsCount = postList.TotalItemsCount,
                PageCount       = postList.PageCount
                                  //,
                                  //previousPageLink,
                                  //nextPageLink
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {//将meta匿名类属性 大写转小写
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));;
            return(Ok(resultAll));
        }