14

i am trying to show an error page when the user uploads a file that is over the limit (see Catching "Maximum request length exceeded")

in the global.asax i want to redirect to a controller action, so something like thisbut it does not work ?:

private void Application_Error(object sender, EventArgs e)
{
    if (GlobalHelper.IsMaxRequestExceededEexception(this.Server.GetLastError()))
    {
        this.Server.ClearError();
        return RedirectToAction("Home","Errorpage");
    }
}
Community
  • 1
  • 1
user603007
  • 11,416
  • 39
  • 104
  • 168

1 Answers1

24

Try like this:

protected void Application_Error()
{
    var exception = Server.GetLastError();
    // TODO: Log the exception or something
    Response.Clear();
    Server.ClearError();

    var routeData = new RouteData();
    routeData.Values["controller"] = "Home";
    routeData.Values["action"] = "ErrorPage";
    Response.StatusCode = 500;
    IController controller = new HomeController();
    var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
    controller.Execute(rc);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I am using above code in Session_Start(). I am using it while redirecting to authenticationfalure.aspx page when authentication fails. But, the home page along with failure page both are coming as out put. how to solve this? – Sai Avinash Oct 22 '13 at 13:23
  • @Darin Dimitrov How could I pass parameter to the action method. I want to pass the 'exception' variable somehow. – mathinvalidnik Jan 10 '14 at 13:20
  • 1
    @mathinvalidnik, you could trivially easy pass the exception as RouteData value as I illustrated in this answer: http://stackoverflow.com/a/5229581/29407 – Darin Dimitrov Jan 10 '14 at 22:03
  • @DarinDimitrov I will try this. The weird thing about IController.Execute is that it doesn't change the url actually. – mathinvalidnik Jan 14 '14 at 15:26
  • @DarinDimitrov Thanks for solution . Do we need to define StatusCode ? If we would do that , would we get it on google webmaster tools report ? – peyman gilmour Aug 23 '16 at 11:38
  • it is possible to add an parameter ? – Muflix Jan 04 '17 at 16:27