Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 557
Muflix Avatar asked Jan 04 '17 16:01

Muflix


People also ask

How do I redirect to a controller action in MVC from global ASAX?

We can redirect to controller actions from Global. asax in ASP.Net MVC 5 using the method - RedirectToControllers. The RedirectToControllers() method provided by MVC 2 + versions. Example, it might help you to understand more about the same.

How do we call function with parameters using the MVC?

There are a number of ways in which you can pass parameters to action methods in ASP.NET Core MVC. You can pass them via a URL, a query string, a request header, a request body, or even a form.

Can we have MVC controller with parameterized constructor?

You need to pass controller namespace (using constructor) so every controller should be same namespace and. All controllers need single parameterized construction which accept ILogger object only. Without that it will throw MissingMethodException .


2 Answers

I have figure it out,

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

and in action just catch that parameter

public ActionResult Index(string message)
like image 133
Muflix Avatar answered Oct 13 '22 05:10

Muflix


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.

like image 33
Sulay Shah Avatar answered Oct 13 '22 03:10

Sulay Shah