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

时间:2012-03-07 11:23:24

标签: asp.net-mvc-3 timeoutexception asynccontroller

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

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

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

我做了这个并且有效

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

最佳方法?

2 个答案:

答案 0 :(得分:3)

我选择了这条路线,与上面代码的不同之处在于我还检查Controller是否为Async,因为如果我们处于长时间的轮询场景中,我们只想以这种方式处理Timeouts。

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

答案 1 :(得分:1)

best 的概念非常主观。我不想谈论它,因为不同的人对它有不同的定义。对我来说,使用自定义异常过滤器是处理这种情况的一种非常好的方法,不会使用异常处理代码污染控制器。