Matias Cicero
Matias Cicero

Reputation: 26331

How to access Response in ApiController

I have the following method:

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

But I can't manage to find any reference to a Response in the ControllerContext.

I could cast the IHttpActionResult to an HttpResponseMessage and easily set the headers there, but I'm not much of a fan of downcasting an interface to an implementation.

Is there a way I can set the response's headers in an ApiController?

Upvotes: 2

Views: 398

Answers (1)

peco
peco

Reputation: 4000

Not completely sure this works since I cant test it right now, but how about this.

Define your custom action result class that decorates the original result and adds the header values:

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

And then pass in the configuration you want through the constructor. Like so:

private async Task<IHttpActionResult> UseHttpCache(Func<Task<IHttpActionResult>> operation)
{
    IHttpActionResult result = await operation();
    var maxAge = TimeSpan.FromHours(1);
    return new CachedResult(result, maxAge);
}

Upvotes: 1

Related Questions