问题描述
我需要在不同的控制器之间共享动作方法.举例如下:
public class AController : Controller { public ActionResult Index() { //print AController - Index } public ActionResult Test() { //print test } } public class BController : Controller { public ActionResult Index() { //print BController - Index } }
两个控制器都有一个不同的索引方法.然而,可以从两个控制器调用测试方法.所以我希望当输入以下URL时,测试()方法将执行:
- acontroller/test
- bcontroller/test
我会感谢如何实现这一目标的任何建议.
推荐答案
假设两个控制器的操作相同,将其重构为公共服务:
public interface ITestService { string Test(); } public TestService: ITestService { public string Test() { // common implementation return "The test result"; } }然后设置依赖注入获取此服务.
您的控制器然后可以使用公共服务.
public class AController : Controller { private readonly ITestService _testService; public AController(ITestService testservice) { _testService = testservice; } public ActionResult Test() { var vm = new TestViewModel(); vm.TestResult = _testService.Test(); return View("Test", vm); } } public class BController : Controller { private readonly ITestService _testService; public BController(ITestService testservice) { _testService = testservice; } public ActionResult Test() { var vm = new TestViewModel(); vm.TestResult = _testService.Test(); return View("Test", vm); } }
因为视图Test.cshtml由两个控制器呈现,它应该放在Views\Shared\文件夹中.
其他推荐答案
您可以如此定义自己的路由: https://docs.microsoft.com/aspnet/core/mvc/controllers/routing
所以你可以定义尽可能多的路线,以指向"Acontroller"内的"测试"方法,如下所示:routes.MapRoute("Atest", "AController/Test", defaults: new { controller = "AController", action = "Test" }); routes.MapRoute("Btest", "BController/Test", defaults: new { controller = "AController", action = "Test" });
但您必须在"默认"路由之前定义它们,因为否则输入的URL将匹配默认路由条件,因此它将进入该路由.
也可以直接在该方法的顶部定义路由.
public class AController : Controller { [Route("/Some/Route")] public ActionResult Test() { } }
其他推荐答案
我想投入替代解决方案.创建一个基本的控制器类以由其他两个继承.无论你有什么,都会有孩子.
public class BaseController : Controller { public ActionResult Index() { //print AController - Index } // Add more methods to be shared between the other controllers } public class AController : BaseController { // Has Index method already from parent // Unique method for A public ActionResult Test() { //print test 1 } } public class BController : BaseController { // Has Index method already from parent // Unique method for B public ActionResult Test() { //print test 2 } }
这在一个地方实现了实际功能.我们使用这种方法对于许多没有问题的项目.