如何使用常规 Web 表单中的 MVC 操作结果(伪造 ControllerContext)?
我们有一个可插入框架,它返回 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);
}
}
您可以从 Web 表单中调用上述内容:
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 该怎么办?
We have a pluggable framework that returns ActionResult
objects that render things to a browser. One late breaking requirement is that our plugins should be callable from a regular ASP.NET Web Forms application.
So far I have come up with this, which works for very basic 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);
}
}
You would call the above from a web form with:
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"));
}
What else do I need to do to hook everything up? For example, what if I wanted to return a ViewResult?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ControllerContext 上没有太多可以伪造的属性。
因此,您只需担心 ActionResult 可能依赖于 RouteData 中存在的任意键。只要您填充 action 和 controller,ViewResult 就应该很高兴,以便它知道在哪里查找视图文件。如果您更改代码以提供包含这些值的 RouteData,则应该没问题。
There aren't too many properties to fake on ControllerContext.
So you're just left to worry that the ActionResult could depend on arbitrary keys being present in RouteData. A ViewResult should be happy as long as you populate action and controller so that it knows where to look for the view file. If you alter your code to provide a RouteData with those values, you should be OK.