在ASP.NET MVC中,从一个控制器调用另一个控制器可以使用以下几种方法:
public class HomeController : Controller
{
private readonly IAnotherController _anotherController;
public HomeController(IAnotherController anotherController)
{
_anotherController = anotherController;
}
public IActionResult Index()
{
// 调用另一个控制器的方法
_anotherController.DoSomething();
return View();
}
}
public interface IAnotherController
{
void DoSomething();
}
public class AnotherController : IAnotherController
{
public void DoSomething()
{
// 执行逻辑
}
}
public class HomeController : Controller
{
public IActionResult Index()
{
// 实例化另一个控制器
var anotherController = new AnotherController();
// 调用另一个控制器的方法
anotherController.DoSomething();
return View();
}
}
public class AnotherController : Controller
{
public void DoSomething()
{
// 执行逻辑
}
}
请注意,在第二种方法中,如果要调用的控制器依赖于其他服务(例如数据库访问),则需要手动实例化这些服务并将它们传递给要调用的控制器。使用依赖注入的方法更加灵活和可测试。