asp.net MVC Redirect actions from inherited controllers to generic base controller views

I have a generic base controller that is inherited by some other controllers.

Is it possible that this request /InheritedController/{Action} redirects to /Base/{Action} ?

Or will the application always try to redirect to InheritedContoller/{Action} even after having executed the code that is in the base controller?

Upvotes: 1

Views: 1331

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239300

You're confusing routes with simple inheritance. The routing framework is fairly simplistic. Given the default route {controller}/{action}/{id}, it will literally find a controller with that name, new it up, and attempt to call the action on it with whatever other request data it has. It neither knows, nor cares, that that this class inherits from a base controller. If you wanted to redirect to the base controller's action of the same name, you would need to override this method on your inherited controller to do a redirect:

public class FooController : BaseController
{
    public override ActionResult Bar()
    {
        return RedirectToAction("Bar", "Base");
    }
}

public class BaseController
{
    public virtual ActionResult Bar()
    {
        return View();
    }
}

Then, when you went to /Foo/Bar, you would be redirected to /Base/Bar. However, importantly, this means that your base controller must be able to be instantiated itself -- it can't be abstract.

For what it's worth, though, just redirecting from the child to the parent calls into question why you're inheriting in the first place. If you want to send someone to the action Base.Bar(), then just use the URL /Base/Bar and be done with it.

Upvotes: 2

Related Questions