Reputation: 817
I'm using Asp.Net Core 3.1 as a Rest Api Service. I used memory cache to store result after calling actions,
The problem is i created custom headers on actions before return the object and i also need to cache this headers, but i cant access it while using OnResultExecuted on action filters
Web api :
[CachingResource(Prefixe = CachingPrefixes.Contents)]
[HttpGet("{typeId}")]
public async Task<IActionResult> Get(int typeId, [FromQuery]GetContentsParams prms)
{
ApiPagedList<C_ContentLoc> items = await _rep.GetItemsLocPaged(typeId, prms);
IEnumerable<ContentDto> dto = _mapper.Map<IEnumerable<ContentDto>>(items);
Response.AddPaginationHeader(items.CurrentPage, items.PageSize, items.TotalCount, items.TotalPages);
return Ok(dto);
}
Add pagination header extension :
public static void AddPaginationHeader(this HttpResponse response, int currentPage, int pageSize, int totalItems, int numberOfPages)
{
var paginationHeader = new PaginationHeader(currentPage, pageSize, numberOfPages, totalItems);
//create header object
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
response.Headers.Add("Pagination", JsonConvert.SerializeObject(paginationHeader, camelCaseFormatter));
//give the client access to this header
response.AddExposeHeader("Pagination");
}
Caching resource filter on result executed :
public override void OnResultExecuted(ResultExecutedContext context)
{
if (!isInCache && !string.IsNullOrEmpty(cacheKey))
{
if (context.Result is OkObjectResult result)
{
bool isExist = context.HttpContext.Request.Headers.TryGetValue("Pagination", out StringValues vs);
if(isExist)
{
//no result !
}
_cache.Set(cacheKey, result.Value);
CachingHelper.SaveCacheKeys(Prefixe, cacheKey, _cache);
}
}
}
Upvotes: 1
Views: 276
Reputation: 24609
You need to read Response
headers, but not Request
bool isExist = context.HttpContext.Response.Headers.TryGetValue("Pagination", out StringValues vs);
Upvotes: 2