I've got a .Net Core (3.1) MVC application, and I'm trying to add a new action to a controller. However, given the architecture of this solution, I'm very limited to what I can change.
Essentially I have an MVC controller, and a class that inherits from this controller that overrides some of the existing actions. That's working fine, but I need to add a new action to this inherited controller, and I cannot find how to set the route up for it.
My main controller is:
public class HomeController : Controller { [HttpGet] public virtual IActionResult Index() { return Json(new { Success = true, Message = "Called HomeController.Index" }); } } My derived class is:
public class HomeControllerExtended : HomeController { public override IActionResult Index() { return Json(new { Success = true, Message = "Called HomeControllerExtended.Index" }); } [HttpGet] public IActionResult DoThis() { return Json(new { Success = true, Message = "Called DoThis" }); } } Accessing /Home/Index returns the JSON with the 'Called HomeControllerExtended.Index' message, which is expected. However, accessing /Home/DoThis results in 404.
I've tried a few ways of adding a new route in Startup.cs, but none make any difference. For example:
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "DoThis", pattern: "{controller=Home}/{action=DoThis}"); }); But this makes no difference.
Firstly, is it possible for new actions to be added like this? And if so, how do I configure the routing to find the new action?
Note that I cannot change HomeController at all, and the new action needs to be able to access the protected methods on HomeController.
DoThisaction as[Route(“Home/DoThis”)].