Determine result type in OnException of controller
Asked Answered
P

1

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

Patristic answered 6/8, 2010 at 15:25 Comment(0)
W
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!

Wiretap answered 6/8, 2010 at 20:27 Comment(2)
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?Taxation
@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.Wiretap

© 2022 - 2024 — McMap. All rights reserved.