多个URL相同的操作方法 [英] Multiple URLs same action method

查看:339
本文介绍了多个URL相同的操作方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在不同的控制器之间共享动作方法。以以下两个控制器为例:

I need to share action methods between different controllers. Take for example the following 2 controllers:

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
     }
}

两个控制器的Index方法都不同。但是,可以从两个控制器中调用Test方法。因此,我希望在输入以下网址时执行Test()方法:

Both controllers have an Index method which is different. The Test method however can be called from both controllers. So I want that when the following urls are entered the Test() method will execute:


  • AController / Test

  • BController / Test

对于实现这一目标的任何建议,我将不胜感激。

I would appreciate any suggestions on how to achieve this.

推荐答案

假定 Test()操作的实现相同对于两个控制器,都将其重构为公共服务:

Assuming the implementation of the Test() action is the same for both controllers, refactor it into a common service:

public interface ITestService {
    string Test();
}

public TestService: ITestService {
    public string Test() {
        // common implementation
        return "The test result";
    }
}

然后设置依赖注入以获取此服务。

Then set up Dependency Injection to acquire this service.

您的控制器随后可以使用公共服务。

Your controllers then can use the common service.

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);
    }
}

因为视图测试。 cshtml 由两个控制器呈现,应放置在 Views\Shared\ 文件夹中。

Because the View Test.cshtml is rendered by both controllers, it should be placed in the Views\Shared\ folder.

这篇关于多个URL相同的操作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆