给header添加信息
思路:1. 使用IUrlHelper urlHelper的urlHelper.Link(routeName,object)方法创建连接(object为routeName使用时需要传入的参数集合的匿名方法,该方法中包含需要添加的各种信息,例如分页、排序、塑形)
例如
urlHelper.Link("GetTouristRoutes", new
{
fields = paramaters.Fields,
orderBy = paramaters.OrderBy,
keyword = paramaters.Keyword,
rating = paramaters.Rating,
pageNumber = paramaters2.PageNumber - 1,//-1是上一页,+1为下一页,否则为当前页
pageSize = paramaters2.PageSize
})
- 使用switch+ResourceUriType.PreviousPage、NextPage、CurrentPage的做法将link信息返回
public static string GenerateTouristRouteResourceURL(
this IUrlHelper urlHelper,//如果单独成方法就用static+传入IUrlHelper 的方式,如果是在已经注入了IUrlHelper 的Controller类内写这个方法,就直接private string,不需要这一行的参数就可以
TouristRouteResourceParamaters paramaters,
PaginationResourceParamaters paramaters2,
ResourceUriType type
)
{
return type switch
{
ResourceUriType.PreviousPage => urlHelper.Link("GetTouristRoutes", new
{
fields = paramaters.Fields,
orderBy = paramaters.OrderBy,
keyword = paramaters.Keyword,
rating = paramaters.Rating,
pageNumber = paramaters2.PageNumber - 1,
pageSize = paramaters2.PageSize
}),
ResourceUriType.NextPage => urlHelper.Link("GetTouristRoutes", new
{
fields = paramaters.Fields,
orderBy = paramaters.OrderBy,
keyword = paramaters.Keyword,
rating = paramaters.Rating,
pageNumber = paramaters2.PageNumber + 1,
pageSize = paramaters2.PageSize
}),
_ => urlHelper.Link("GetTouristRoutes", new
{
fields = paramaters.Fields,
orderBy = paramaters.OrderBy,
keyword = paramaters.Keyword,
rating = paramaters.Rating,
pageNumber = paramaters2.PageNumber,
pageSize = paramaters2.PageSize
})
};
}
- 在返回Dto的时候调用并添加到Header中
string previousPageLink = touristRoutesFromRepo.HasPrevious ? _urlHelper.GenerateTouristRouteResourceURL(paramaters, paramaters2, ResourceUriType.PreviousPage) : null;
string nextPageLink = touristRoutesFromRepo.HasNext ? _urlHelper.GenerateTouristRouteResourceURL(paramaters, paramaters2, ResourceUriType.NextPage) : null;
// x-pagination
var paginationMetadata = new
{
previousPageLink,
nextPageLink,
totalCount = touristRoutesFromRepo.TotalCount,
pageSize = touristRoutesFromRepo.PageSize,
currentPage = touristRoutesFromRepo.CurrentPage,
totalPages = touristRoutesFromRepo.TotalPages
};
Response.Headers.Add("x-pagination", Newtonsoft.Json.JsonConvert.SerializeObject(paginationMetadata));