10

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

Chris Dellinger
  • 2,292
  • 4
  • 25
  • 33

1 Answers1

8

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!

uvita
  • 4,124
  • 1
  • 27
  • 23
  • 1
    Given two actions with the same name, such as Edit and Edit (one GET, one POST), this gives an AmbiguousMatchException. Is there a way to determine from the context which action was called? – yoozer8 Jan 14 '14 at 15:27
  • 3
    @Jim you can use type.GetMethods().Where(m=>m.Name.Equals(action)) in that case and obtain the right method by knowing the verb that was used in the current request and looking at the attributes of each method. – uvita Jan 15 '14 at 12:58