0

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.

3
  • 1
    Attach the route attribute at DoThis action as [Route(“Home/DoThis”)]. Commented Jan 15, 2021 at 11:52
  • @user1672994 Of course! Thank you, yes, that did the trick. I knew it'd be something really straight-forward. Commented Jan 15, 2021 at 11:54
  • 1
    posted that as answer. Commented Jan 15, 2021 at 11:55

1 Answer 1

2

You can attach the route attribute over DoThis action as shown below

[Route("Home/DoThis")] [HttpGet] public IActionResult DoThis() { return Json(new { Success = true, Message = "Called DoThis" }); } 

With above now you can access the DoThis action using /Home/DoThis path.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.