首页 新闻 会员 周边

ASP.NET Core 中 Controller A Action 中如何返回 Controller B Action

0
悬赏园豆:50 [已解决问题] 解决于 2022-04-21 07:31

请问在 ASP.NET Core 如何在一个 Controller 的 Action 中返回另外一个 Controller 的 Action?

dudu的主页 dudu | 高人七级 | 园豆:30994
提问于:2022-04-20 22:52
< >
分享
最佳答案
1
  • Controller 注册为service, 在A里面注入B 直接call method.
  • A里面new B 并给httpcontext赋值然后call method
收获园豆:50
czd890 | 专家六级 |园豆:14412 | 2022-04-20 23:38

验证通过,这样的确可以。

Program.cs

builder.Services.AddScoped<BController>();

AController.cs

public class AController : Controller
{
    public IActionResult Index()
    {
        var bConroller = HttpContext.RequestServices.GetRequiredService<BController>();
        return bConroller.Index();
    }
}

BController.cs

public class BController : Controller
{
    public IActionResult Index()
    {
        return Ok("This is BController");
    }
}
dudu | 园豆:30994 (高人七级) | 2022-04-21 07:31

@dudu: 注册为services有一个快捷方法。大概是 services.AddConteoller().asServices() 之类的一个扩张方法

czd890 | 园豆:14412 (专家六级) | 2022-04-21 08:38

@czd890: 实际只有一个 Controller 有这个需求

dudu | 园豆:30994 (高人七级) | 2022-04-21 09:31
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册