如何在ASP.NET MVC5应用程序中处理请求超时?

时间:2016-06-21 23:03:15

标签: c# asp.net asp.net-mvc asp.net-mvc-5 request-timed-out

到目前为止,我已尝试以下方法 - 1)添加了自定义属性以处理超时。

 public class TimeOutFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        System.Web.HttpContext.Current.GetType().GetField("_timeoutState", System.Reflection.BindingFlags.Instance |
        System.Reflection.BindingFlags.NonPublic).SetValue(System.Web.HttpContext.Current, 1);

        base.OnActionExecuting(filterContext);
    }
}

在Global.asax中添加了以下内容

filters.Add(new TimeOutFilter());

使用[TimeOutFilter]属性来装饰控制器

2)添加了AsyncTimeout属性以装饰控制器/ Action,如下所示:

[AsyncTimeout(10)]

3)将executionTimeout设置为web.config文件中的值。

<httpRuntime targetFramework="4.5" maxRequestLength="10240" executionTimeout="10" />

4)将HttpContext.Server.ScriptTimeout设置为控制器中的某个值。

HttpContext.Server.ScriptTimeout = 10;

使用第1点中的步骤,我可以在请求超时时将用户重定向到登录屏幕。但这不是我想要的。

我正在寻找在请求超时发生时获取或触发异常。

有人可以告诉我,如果我们有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

请勿使用rude thread abort behavior(1)和(4)。

AsyncTimeout属性(2)很好但只是声明(如web.config(3)中的executionTimeout)超时持续时间。

在mvc5的完全异步管道中,只是一种有效的超时操作方法:使用CancellationTokens投掷!

您可以通过参数或Request.TimedOutTokenResponse.ClientDisconnectedToken属性获取这些令牌。

blog post给了我很多帮助。