使用AsyncController处理超时的最佳方法

使用AsyncController处理超时的最佳方法

问题描述:

我的MVC3项目中有很长时间的轮询控制器.它的超时设置为30秒.我有一个HandleErrorAttribute实现,可以处理所有错误的记录.

I have a long time polling controller in my MVC3 project. It has its timeout set to 30 seconds. I have a HandleErrorAttribute implementation that handles logging of all errors.

由于timout抛出TimeoutException,这意味着它们将在日志中显示.

Since the timout throws a TimeoutException it means these will be presented in the log.

我需要在HandleErrorAttribute类获取它之前拦截此错误,并返回一个json对象而不是500错误页面.最好的方法是什么?

I need to intercept this error before my HandleErrorAttribute class gets it and return a json object instead of the 500 error page. Whats the best approach for this?

我做到了,而且有效

public class HandleTimeout : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if(filterContext.Exception is TimeoutException)
        {
            filterContext.Result = new { Timeout = true }.AsJson();
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = 200;
        }

        base.OnException(filterContext);
    }
}

最好的方法?

我选择了这条路线,与上面的代码不同的是,我还检查Controller是否是异步的,因为我们只想以这种方式处理超时如果我们处于长时间轮询的情况.

I went with this route, the difference from my above code is that I also check if the Controller is Async, because we only want to handle Timeouts in this fashion if we are in a long time polling scenarios.

public class HandleTimeout : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if(filterContext.Exception is TimeoutException && filterContext.Controller is AsyncController)
        {
            filterContext.HttpContext.Response.StatusCode = 200;
            filterContext.Result = new { Timeout = true }.AsJson();
            filterContext.ExceptionHandled = true;
        }

        base.OnException(filterContext);
    }
}