Dan
Dan

Reputation: 75

Is there (or will there soon be) a ResponseCache equivalent in Azure Functions?

Is there an equivalent of the ASP.NET Core ResponseCache attribute in Azure functions. I'd like my function to add a cache control header.

Similar to this for ASP.NET Core:

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.responsecacheattribute?view=aspnetcore-5.0

Or is there a workaround that is compatible with Azure Functions V3?

Thanks.

Upvotes: 0

Views: 877

Answers (1)

Jim Xu
Jim Xu

Reputation: 23141

If you want to implement Response Cache in Azure function, we can use the arrtibute FunctionInvocationFilterAttribute to implement it.

For example

  1. Implement ResponseCacheAttribute
 class FunctionResponseCacheAttribute : FunctionInvocationFilterAttribute
    {
        private readonly int _duration;
        private readonly ResponseCacheLocation _cacheLocation;
        public FunctionResponseCacheAttribute(
            int duration,
            ResponseCacheLocation cacheLocation)
        {
            _duration = duration;
            _cacheLocation = cacheLocation;
        }
        public override async Task OnExecutedAsync(
            FunctionExecutedContext executedContext,
            CancellationToken cancellationToken)
        {
            if (!(executedContext.Arguments.First().Value is HttpRequest request))
                throw new ApplicationException(
                    "HttpRequest is null. ModelBinding is not supported, " +
                    "please use HttpRequest as input parameter and deserialize " +
                    "using helper functions.");
            var headers = request.HttpContext.Response.GetTypedHeaders();
            var cacheLocation = executedContext.FunctionResult?.Exception == null
                ? _cacheLocation
                : ResponseCacheLocation.None;
            switch (cacheLocation)
            {
                case ResponseCacheLocation.Any:
                    headers.CacheControl = new CacheControlHeaderValue()
                    {
                        MaxAge = TimeSpan.FromSeconds(_duration),
                        NoStore = false,
                        Public = true
                    };
                    break;
                case ResponseCacheLocation.Client:
                    headers.CacheControl = new CacheControlHeaderValue()
                    {
                        MaxAge = TimeSpan.FromSeconds(_duration),
                        NoStore = false,
                        Public = true
                    };
                    break;
                case ResponseCacheLocation.None:
                    headers.CacheControl = new CacheControlHeaderValue()
                    {
                        MaxAge = TimeSpan.Zero,
                        NoStore = true
                    };
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            await base.OnExecutedAsync(executedContext, cancellationToken);
        }
    }
  1. Usage
[FunctionName("Function1")]
        [FunctionResponseCache(60 * 60, ResponseCacheLocation.Any)]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
        }

enter image description here


Update According to the situation, I think you can add the following code in the your function to implement it

 [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

...
            var resHeaders = req.HttpContext.Response.GetTypedHeaders();
            resHeaders.CacheControl = new CacheControlHeaderValue()
            {
                MaxAge = TimeSpan.FromSeconds(3600),
                NoStore = false,
                Public = true
            };
 ...
        }

Upvotes: 1

Related Questions