Mvcのコントローラーから別のコントローラーアクションを呼び出す方法 質問する

Mvcのコントローラーから別のコントローラーアクションを呼び出す方法 質問する

コントローラー A からコントローラー B のアクション FileUploadMsgView を呼び出して、それにパラメーターを渡す必要があります。

コントローラー B には行きませんFileUploadMsgView()

コードは次のとおりです:

コントローラーA:

private void Test()
{
    try
    {   //some codes here
        ViewBag.FileUploadMsg = "File uploaded successfully.";
        ViewBag.FileUploadFlag = "2";
        RedirectToAction("B", "FileUploadMsgView", new { FileUploadMsg = "File   uploaded successfully" });
    }
}

コントローラB(受信部):

public ActionResult FileUploadMsgView(string FileUploadMsg)
{
    return View();
}

ベストアンサー1

@mxmissile が承認された回答へのコメントで述べているように、コントローラーを新規に作成しないでください。IoC 用に設定された依存関係が失われ、 がなくなるためですHttpContext

代わりに、次のようにコントローラーのインスタンスを取得する必要があります。

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

.NET Core / .NET 5+ では、次のようにコントローラーを挿入する必要があります。

public class ControllerA : ControllerBase
{
    public ControllerA(ControllerB other) { _other = other; }

    public ActionResult MyMethod() { other.SomeMethod(); }
}  

ただし、一般的に、別のコントローラーを呼び出すことはアンチパターンであり、コントローラーの重要な部分を共有サービスに抽象化し、必要な場所に挿入する方がよいでしょう。


//interface optional. register as AddSingleton<IMyService, MyService>(); or scoped or w/e
public interface IMyService
{
    string GetValue();
}
public class MyService : IMyService
{
    public string GetValue()
    {
        return "Query some database or anything else";
    }
}

public class ControllerA(IMyService _service)
{
    public ActionResult GetValueA()
    {
        var somethingDifferentFromB = _service.GetValue() + "_controllera";
        return Ok(somethingDifferentFromB);
    }
}

public class ControllerB(IMyService _service)
{
    public ActionResult GetValueB()
    {
        return Ok(_service.GetValue());
    }
}

おすすめ記事