Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NOtherDev/3766954 to your computer and use it in GitHub Desktop.
Save NOtherDev/3766954 to your computer and use it in GitHub Desktop.
ASP.NET MVC: Replacing the default ActionInvoker to do something useful with non-ActionResult return types
// ASP.NET MVC: Replacing the default ActionInvoker to do something useful with non-ActionResult return types
// See more: http://notherdev.blogspot.com/2012/09/non-actionresult-return-type-aspnet-mvc.html
public class MyControllerFactory : DefaultControllerFactory
{
public override IController CreateController(RequestContext context, string controllerName)
{
var controller = base.CreateController(context, controllerName);
return ReplaceActionInvoker(controller);
}
private IController ReplaceActionInvoker(IController controller)
{
var mvcController = controller as Controller;
if (mvcController != null)
mvcController.ActionInvoker = new ControllerActionInvokerWithDefaultJsonResult();
return controller;
}
}
public class ControllerActionInvokerWithDefaultJsonResult : ControllerActionInvoker
{
public const string JsonContentType = "application/json";
protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
{
if (actionReturnValue == null)
return new EmptyResult();
return (actionReturnValue as ActionResult) ?? new ContentResult()
{
ContentType = JsonContentType,
Content = JsonConvert.SerializeObject(actionReturnValue)
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment