我有以下方法:
private async Task<IHttpActionResult> UseHttpCache(Func<Task<IHttpActionResult>> operation) {
IHttpActionResult result = await operation();
//Add HTTP Headers here...
}
但我在
Response
中找不到对aControllerContext
的任何引用。我可以将
IHttpActionResult
转换为HttpResponseMessage
并在那里轻松设置头,但我不太喜欢将接口向下转换为实现。有没有办法在
ApiController
中设置响应的头? 最佳答案
我现在还不能测试它,所以不完全确定它是否有效,但是这个怎么样。
定义自定义操作结果类,该类修饰原始结果并添加头值:
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);
}