ASP.NET MVC: Call one controller action from another, with ActionFilters applied

core picture core · Apr 18, 2013 · Viewed 8.5k times · Source

Take a look at the code below.

When Get() calls Foobar() and Foobaz(), the ActionFilters that decorate Foobar() and Foobaz() are not invoked.

How can I call these other two controller actions from within Get() in a way that also causes the SomeAction and AnotherAction filters to execute?

public class Features : Controller
{
    [SomeAction]
    public bool Foobar(string id = null)
    {
        return true;
    }

    [AnotherAction]
    public bool Foobaz()
    {
        return false;
    }

    public JsonResult Get()
    {
        return this.JsonResult(new Dictionary<string, bool>() 
        {
            { "foobar", this.Foobar() },
            { "foobaz", this.Foobaz() }
        });
    }
}

Answer

Chris Pratt picture Chris Pratt · Apr 18, 2013

Controller actions aren't meant to be used as methods. In order for them to function properly they must be called within the request cycle. Perhaps your example is too simplistic, but it looks like you're trying to use these "actions" as just standard methods. While a controller can technically have a method that's never actually meant to be exposed as a route, it's not a good idea to do this sort of thing. Move the logic off into your model or some helper class.