我有以下方法:

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);
}

10-08 06:48