Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine result type in OnException of controller

I'm working on an MVC.NET 2.0 project where I'm trying to put in some special error handling logic in the OnException method of the controller. Basically I want to be able to determine the result type of the controller method in which the unhandled exception was raised, so that I can return error data in a certain format dependent upon the type (json for JsonResult and html for ActionResult). Can anyone point me to a way to determine that type? I would greatly appreciate any help.

Thanks in advance

like image 459
Chris Dellinger Avatar asked Aug 06 '10 15:08

Chris Dellinger


People also ask

How do I find controller model value?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.

How does the controller know which view to return?

MVC by default will find a View that matches the name of the Controller Action itself (it actually searches both the Views and Shared folders to find a cooresponding View that matches). Additionally, Index is always the "default" Controller Action (and View).

How many action results are there in MVC?

There are 7 types of content returning results: ViewResult. PartialViewResult. ContentResult.


1 Answers

Assuming you didn´t change the default routing:

protected override void OnException(ExceptionContext filterContext)
{
    var action = filterContext.RouteData.Values["action"].ToString();
    var type = filterContext.Controller.GetType();
    var method = type.GetMethod(action);
    var returnType = method.ReturnType;
    //...do whatever here...
}

Good luck!

like image 135
uvita Avatar answered Oct 14 '22 08:10

uvita