Reputation: 75
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:
Or is there a workaround that is compatible with Azure Functions V3?
Thanks.
Upvotes: 0
Views: 877
Reputation: 23141
If you want to implement Response Cache in Azure function, we can use the arrtibute FunctionInvocationFilterAttribute
to implement it.
For example
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);
}
}
[FunctionName("Function1")]
[FunctionResponseCache(60 * 60, ResponseCacheLocation.Any)]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
}
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