我们有一个可返回的可插入框架 ActionResult 将事物呈现给浏览器的对象。一项最新的要求是我们的插件应该可以从常规 ASP.NET Web 窗体应用程序中调用。

到目前为止,我已经想出了这个,它适用于非常基本的 ActionResults:

public class ActionResultTranslator {

    HttpContextBase _context;

    public ActionResultTranslator(HttpContextBase context ) {

        _context = context;
    }

    public void Execute(ActionResult actionResult) {

        ControllerContext fakeContext = new ControllerContext();
        fakeContext.HttpContext = _context;            

        actionResult.ExecuteResult(fakeContext);        
    }
}

您可以通过以下方式从网络表单调用上述内容:

protected void Page_Load(object sender, EventArgs e) {
   HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);
   var translator = new ActionResultTranslator(contextWrapper);
   translator.Execute(new RedirectResult("http://google.com"));     
}

我还需要做什么来连接一切?例如,如果我想返回一个 ViewResult 该怎么办?

有帮助吗?

解决方案

ControllerContext 上没有太多可以伪造的属性。

  • HttpContext - 你已经解决了这个问题
  • 控制器 - 据我所知,没有标准 ActionResults 关心这是否为空
  • 请求上下文 - 如果留空,将自动填充
  • 路线数据 - 如果留空,将填充空集合。

因此,您只需担心 ActionResult 可能依赖于 RouteData 中存在的任意键。只要您填充,ViewResult 就应该很高兴 行动控制器 这样它就知道在哪里寻找视图文件。如果您更改代码以提供包含这些值的 RouteData,则应该没问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top