Customize headers with IHttpActionResult?

1

Currently I have a method that returns a list of cities, the method I have it in the following way:

[ResponseType(typeof(List<Cities>))]
public IHttpActionResult GetSourceCities(int idPais)
{
    try
    {
        var cities = GetCities(idPais);
        return cities == null ? Ok(new List<Cities>()): Ok(cities);
    }
        catch (Exception ex)
        {
            Log.Write(ex.message);
            return NotFound();
        }
    }

I want to implement cache so that you can access the list of cities quickly and efficiently. Now, to do it easily, change the type of response, from an IHttpActionResult to HttpResponseMessage so that you can add the cache attribute in the header.

[ResponseType(typeof(List<Cities>))]
public HttpResponseMessage GetSourceCities(int idPais)
{
    try
    {
        var cities = GetCities(idPais);
        //return cities == null ? Ok(new List<Cities>()): Ok(cities);
        var httpResponseMessage = Request.CreateResponse<List<Cities>>(HttpStatusCode.OK, cities); 
        httpResponseMessage.Headers.CacheControl = new CacheControlHeaderValue() 
            { 
                MaxAge = TimeSpan.FromMinutes(15) 
            };
        return httpResponseMessage;

    }
        catch (Exception ex)
        {
            Log.Write(ex.message);
            //return NotFound();
            var httpResponseMessage = Request.CreateResponse(HttpStatusCode.NotFound);
            return httpResponseMessage;
        }
    }

Now the question is: I do not want to use HttpResponseMessage, how to customize the IHttpActionResult to implement cache?

    
asked by Makito 27.04.2016 в 21:03
source

1 answer

1

What you could do is create a ActionFilter to add the cache headers to the response

The implementation of the filter would be as follows:

public class CacheControlAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public int MaxAge { get; set; }

    public CacheControlAttribute()
    {
        MaxAge = 3600;
    }

    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        context.Response.Headers.CacheControl = new CacheControlHeaderValue()
        {
            Public = true,
            MaxAge = TimeSpan.FromSeconds(MaxAge)
        };

        base.OnActionExecuted(context);
    }
} 

Your action based on IHttpActionResult would look like this:

[ResponseType(typeof(List<Cities>))]
[CacheControl(MaxAge = 900)]
public IHttpActionResult GetSourceCities(int idPais)
{
    try
    {
        var cities = GetCities(idPais);
        return cities == null ? Ok(new List<Cities>()): Ok(cities);
    }
    catch (Exception ex)
    {
        Log.Write(ex.message);
        return NotFound();
    }
}
    
answered by 27.04.2016 в 22:09