Global.asax redirecttoroute not working

I want to use a custom route in my global.asax with response.redirecttoroute, but it doesn't work. My RouteConfig has the following:

routes.MapRoute(
            name: "Error",
            url: "Error/{action}/{excep}",
            defaults: new { action = "Index", excep = UrlParameter.Optional }
        );

      

And in my global.asax I am doing the following:

Response.RedirectToRoute("Error", new { action="Index", excep=ex.Message });

      

In my ErrorController I have:

public ActionResult Index(string excep)
    {
        ViewBag.Exception = excep;

        return View();
    }

      

And in my index view for the error, I am throwing ViewBag.Exception to show the exception.

When I use:

Response.Redirect("/Error/Index/0/"+ex.Message, true);

      

And use this in my controller:

public ActionResult Index(int? id,string excep)
    {
        ViewBag.Exception = excep;

        return View();
    }

      

It works, but it has to do with the default route and not what I want. Why does it work with redirection but not redirecttoroute?

+3


source to share


3 answers


I faced the same problem, but now I have found a solution. Maybe you can try this: just rename the class names or variable names according to your needs. Please note that after changing anything from your Global.asax, clear your browser cache. Hope this helps.

Global.asax

  public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
       //Make sure this route is the first one to be added
        routes.MapRoute(
           "ErrorHandler",
           "ErrorHandler/{action}/{errMsg}",
           new { controller = "ErrorHandler", action = "Index", errMsg=UrlParameter.Optional}
           );
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

      

After an exception is thrown, unhandles will redirect the response to your error handler from your Global.asax Application_Error event

 protected void Application_Error(object sender, EventArgs e)
        {
            var errMsg = Server.GetLastError().Message;
            if (string.IsNullOrWhiteSpace(errMsg)) return;
            //Make sure parameter names to be passed is are not equal
            Response.RedirectToRoute("ErrorHandler", new { strErrMsg=errMsg });
            this.Context.ClearError();
        }

      

Error handler controller



public class ErrorHandlerController : Controller
    {

        public ActionResult Index(string strErrMsg)
        {
            ViewBag.Exception = strErrMsg;
            return View();
        }

    }

      

To test your error handler on your ActionResult index from HomeController add this code.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //just intentionally add this code so that exception will occur
            int.Parse("test");
            return View();
        }
    }

      

The output will be

enter image description here

+3


source


This other question has a pretty good answer: How is RedirectToRoute supposed to be used?



I would try to add Response.End()

after RedirectToRoute

and see if that works.

+2


source


this is how I solved my problem with MVC 4:

RouteConfig.cs

    routes.MapRoute(
            name: "ErrorHandler",
            url: "Login/Error/{code}",
            defaults: new { controller = "Login", action = "Error", code = 10000 } //default code is 10000
        );

    routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
        );

      

Global.asax.cs

    protected void Application_Start()
    {
            //previous code
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            this.Error += Application_Error; //register the event
    } 

    public void Application_Error(object sender, EventArgs e)
    {
            Exception exception = Server.GetLastError();
            CustomException customException = (CustomException) exception;
            //your code here

            //here i have sure that the exception variable is an instance of CustomException.
            codeErr = customException.getErrorCode(); //acquire error code from custom exception

            Server.ClearError();

            Response.RedirectToRoute("ErrorHandler", new
                                    {
                                            code = codeErr
                                    });
            Response.End();
    }

      

Here's the trick: be sure to put Response.End () at the end of the Application_Error method . Otherwise, the redirection to the route will not work correctly. In particular, the code parameter will not be passed to the controller action method.

LoginController

    public class LoginController : Controller
    {
           //make sure to name the parameter with the same name that you have passed as the route parameter on Response.RedirectToRoute method.
           public ActionResult Error(int code)
           {
                   ViewBag.ErrorCode = code;

                   ViewBag.ErrorMessage = EnumUtil.GetDescriptionFromEnumValue((Error)code);

                   return View();
           }
    }

      

0


source







All Articles