用于HTTP 503状态代码的ASP.NET MVC OutputCache [英] ASP.NET MVC OutputCache for HTTP 503 status code

查看:67
本文介绍了用于HTTP 503状态代码的ASP.NET MVC OutputCache的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ASP.NET MVC 5.0创建服务器监视应用程序.如果服务器不可用,我想返回HTTP 503状态代码以及带有服务器状态详细信息的Json内容.我也想使用ASP.NET输出缓存在特定持续时间(例如10秒)中缓存此响应.

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).

我面临的问题是,如果状态代码是HTTP 200,则ASP.NET MVC 5.0中的OutputCache过滤器可以工作,而如果HTTP 503,则不能.下面是我在应用程序中使用的MVC操作的示例代码.

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.

不是HTTP 200以外的HTTP状态代码是否不可缓存?是否有任何其他机制可以通过Ouput缓存或任何IIS设置来缓存HTTP 503响应?

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

推荐答案

据我所知,OutputCache仅缓存有效的响应.我快速浏览了源代码,但看不到任何明显的方式可以替代此行为.

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.

类似的东西:

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

应该做到这一点.如果围绕SO进行搜索,您会发现许多有用的Cache包装器,这些包装器可以插入和检索一些尼克尔".

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".

这篇关于用于HTTP 503状态代码的ASP.NET MVC OutputCache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆