MVC最大请求长度超出异常 - 调用其他控制器操作

时间:2014-04-29 19:47:53

标签: c# asp.net-mvc

我正在试图弄清楚如何处理Maximum request length exceeded异常。如果抛出该异常,我必须调用其他控制器的操作。问题是, 没有调用UploadError操作 - 为什么?

以下是代码段:

<httpRuntime maxRequestLength="1024" /> 
...
<requestLimits maxAllowedContentLength="1048576"/>


    const int TimedOutExceptionCode = -2147467259;
    public bool IsMaxRequestExceededException(Exception e)
    {
        // unhandled errors = caught at global.ascx level
        // http exception = caught at page level

        Exception main;
        var unhandled = e as HttpUnhandledException;

        if (unhandled != null && unhandled.ErrorCode == TimedOutExceptionCode)
        {
            main = unhandled.InnerException;
        }
        else
        {
            main = e;
        }


        var http = main as HttpException;

        if (http != null && http.ErrorCode == TimedOutExceptionCode)
        {
            // hack: no real method of identifying if the error is max request exceeded as 
            // it is treated as a timeout exception
            if (http.StackTrace.Contains("GetEntireRawContent"))
            {
                // MAX REQUEST HAS BEEN EXCEEDED
                return true;
            }
        }

        return false;
    }


    protected void Application_Error()
    {
        var exception = Server.GetLastError();
        var routeData = new RouteData();

        if (exception.GetType() == typeof(UploadException) || IsMaxRequestExceededException(exception))
        {
            exception = new UploadException(exception.Message);
            Response.Clear();
            Server.ClearError();
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = "UploadError";
            routeData.Values["exception"] = exception;

            IController errorsController = new ErrorController();
            var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
            errorsController.Execute(rc);
            return;
        }
    }

public class ErrorController : Controller
{
    public ActionResult UploadError(UploadException exception)
    {
        return Content(exception.Message, "text/plain");
    }
}

1 个答案:

答案 0 :(得分:0)

看看这个答案:

https://stackoverflow.com/a/679427/685319

解决了问题。