在Azure函数中是否存在与ASP.NET核心ResponseCache属性等价的内容。我希望我的函数添加一个缓存控制头。
与ASP.NET核心类似:
或者有一个与Azure函数V3兼容的解决方案?
谢谢。
发布于 2021-01-07 05:39:10
如果您想在Azure函数中实现响应缓存,我们可以使用arrtibute FunctionInvocationFilterAttribute来实现它。
例如
实现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)
{
}

根据情况更新,我认为您可以在函数中添加以下代码来实现它
[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
};
...
}https://stackoverflow.com/questions/65588216
复制相似问题