How to create controller object and execute action with parameter from global.asax

1.6k views Asked by At

I have this code in global.asax

 protected void Application_Error(object sender, EventArgs e)
        {
            // ...
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Home");
            routeData.Values.Add("action", "Error");

            IController controller = new Controllers.HomeController();
            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

        }

how can I add parameter to Action method / RouteData ? I would like to show exception message to the user.

2

There are 2 answers

0
Muflix On BEST ANSWER

I have figure it out,

routeData.Values.Add("message", exception.Message);

and in action just catch that parameter

public ActionResult Index(string message)
3
Sulay Shah On

To show the custom error page you need to change the web.config.

<system.web> <customErrors mode="On" defaultRedirect="~/Error"> <error redirect="~/Error/NotFound" statusCode="404" /> </customErrors> </system.web>

You can create error pages for different status code.

Make sure you have controller and action method to return view.

After Application_error MVC it self will redirect to the same page as described in web.config.

Please refer this link for more information.