如何在 ApiController 中访问响应

本文关键字:访问 响应 ApiController | 更新日期: 2023-09-27 18:32:11

>我有以下方法:

private async Task<IHttpActionResult> UseHttpCache(Func<Task<IHttpActionResult>> operation) {
      IHttpActionResult result = await operation();
      //Add HTTP Headers here...
}

但是我无法在ControllerContext中找到任何对Response的引用.

我可以将IHttpActionResult转换为HttpResponseMessage并在那里轻松设置标头,但我不太喜欢将接口向下转换为实现。

有没有办法在ApiController中设置响应的标头?

如何在 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);
}