我有以下方法:
private async Task<IHttpActionResult> UseHttpCache(Func<Task<IHttpActionResult>> operation) {
IHttpActionResult result = await operation();
//Add HTTP Headers here...
}
但我无法找到Response
中对ControllerContext
的任何引用。
我可以将IHttpActionResult
转换为HttpResponseMessage
并轻松设置标题,但我并不喜欢将广播转换为实现的接口。
有没有办法在ApiController
?
答案 0 :(得分:1)
由于我现在无法测试,所以不完全确定这是有效的,但是这个怎么样。
定义自定义操作结果类,用于修饰原始结果并添加标题值:
public class CachedResult : IHttpActionResult
{
private readonly IHttpActionResult _decorated;
private readonly TimeSpan _maxAge;
public CachedResult(IHttpActionResult decorated, TimeSpan maxAge)
{
_decorated = decorated;
_maxAge = maxAge;
}
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = await _decorated.ExecuteAsync(cancellationToken);
response.Headers.CacheControl = new CacheControlHeaderValue
{
Public = true,
MaxAge = _maxAge
};
return response;
}
}
然后通过构造函数传递您想要的配置。像这样:
private async Task<IHttpActionResult> UseHttpCache(Func<Task<IHttpActionResult>> operation)
{
IHttpActionResult result = await operation();
var maxAge = TimeSpan.FromHours(1);
return new CachedResult(result, maxAge);
}