Gaurav
Gaurav

Reputation: 915

ASP.NET MVC OutputCache for HTTP 503 status code

I want to create a server monitoring application using ASP.NET MVC 5.0. In case the server is unavailable I want to return HTTP 503 status code along with a Json content with details of server state. Also I want to cache this response using ASP.NET Output Cache for specific duration(say 10 seconds).

The issue I am facing is that OutputCache filter in ASP.NET MVC 5.0 works if status code is HTTP 200 but not if HTTP 503. Following is the sample code for MVC action which I am using in my application.

Are HTTP status code other than HTTP 200 not cacheable? Is there any alternate mechanism to cache HTTP 503 response either through Ouput Cache or any IIS setting?

[OutputCache(Duration = 10, VaryByParam = "*")]
public ActionResult GetServerStatus(string serverId)
{
    var serverStatus = .... //JSON object
    if(serverStatus.IsAvailable)
    {
        this.Response.StatusCode = (int)HttpStatusCode.OK;
    }
    else
    {
        this.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
    }
    return Json(serverStatus);
}

Upvotes: 1

Views: 1705

Answers (1)

James Hull
James Hull

Reputation: 3689

As far as I know OutputCache only caches valid responses. I had a quick dig into the source code and I can't see any obvious way of overriding this behaviour.

I imagine the simplest answer is to cache the server status yourself.

Something like:

public ActionResult GetServerStatus(string serverId)
{
    string serverStatus = Cache["someKey"];
    if(serverStatus == null)
    {
         serverStatus = ...;
         // Use Cache.Insert for setting duration etc
         Cache["someKey"] = serverStatus;
    }

    if(serverStatus.IsAvailable)
    {
        this.Response.StatusCode = (int)HttpStatusCode.OK;
    }
    else
    {
        this.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
    }

    return Json(serverStatus);
}

Should do the trick. If you have a search around SO you'll find a number of helpful wrappers for Cache which makes inserting and retrieving a little "nicer".

Upvotes: 2

Related Questions