gpt4 book ai didi

c# - 如何以编程方式执行 Controller 的操作方法?

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:48 25 4
gpt4 key购买 nike

我正在尝试以编程方式执行 Controller 的操作方法,但我不确定该怎么做。

场景:当我的 ControllerFactory 找不到 Controller 时,我希望它手动执行一个简单的自定义 Controller 上的单一操作方法。我不想依赖使用任何路由数据来确定 Controller /方法......因为该路由可能尚未连接。

例如。

// NOTE: Error handling removed from this example.
public class MyControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
IController result = null;

// Try and load the controller, based on the controllerType argument.
// ... snip
// Did we retrieve a controller?
if (controller == null)
{
result = new MyCustomController();
((MyCustomController)result).Execute404NotFound(); // <-- HERE!
}

return result;
}
}

.. 那个方法是..

public static void Execute404NotFound(this Controller controller)
{
result = new 404NotFound();
// Setup any ViewData.Model stuff.
result.ExecuteResult(controller.ControllerContext); // <-- RUNTIME
// ERROR's HERE
}

现在,当我运行 Controller 工厂时找不到 Controller ,然后我手动创建自己的基本 Controller 。然后,我在此 Controller 实例上调用扩展方法“Execute404NotFound”。没关系......直到它运行 ExecuteResult(..) 方法。为什么? Controller 没有 ControllerContext 数据。因此,ExecuteResult 崩溃,因为它需要一些 ControllerContext

那么 - 有人可以帮我吗?看看我做错了什么。

记住 -> 我正在尝试让我的 Controller 工厂手动/以编程方式调用 Controller 上的方法,该方法当然会返回 ActionResult。

请帮忙!

更新:

我还试图避免更常见的解决方案,即使用 catchall 或抛出在 Application_Exception 部分处理的异常。我不认为他们应该是处理这个问题的正确方法..考虑到我们知道问题是什么,因此我们应该当场处理它。

最佳答案

如果您手动创建 Controller ,则还必须手动为 Controller 提供上下文。

您走在正确的轨道上,但您将需要更多代码才能完成它。前阵子我自己经历过这个,关于这个 thread on how to instantiate and fake a request to a controller 有一堆非常详尽的代码。 .

如果您只是想在 404 上运行一些代码,那么您的方法似乎有些矫枉过正。你不能做 something like this

关于c# - 如何以编程方式执行 Controller 的操作方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2638841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com