什么是ActionResult的返回类型的呢? [英] What's the point of ActionResult return type?

查看:1096
本文介绍了什么是ActionResult的返回类型的呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是返回的ActionResult行动的意义呢?

What is the point of an action returning ActionResult?

推荐答案

返回一个ActionResult,而不是只是在做什么的ActionResult的是做(即直接使用的Response.Redirect或试图直接通过响应的OutputStream呈现出查看)给你一个人很好的优势:单元测试是真的很容易,特别是因为你通常不需要Web服务器进行单元测试MVC项目

Returning an ActionResult instead of "just doing whatever the ActionResult is doing" (i.e. using Response.Redirect directly or trying to render out a View through the Response OutputStream directly) gives you one really nice advantage: Unit Testing is really easy on that, especially since you normally do not need a web server to unit test MVC Projects.

附录:的作为一个重定向的例子:

Addendum: As an example for a redirect:

如果您

return Redirect(newUrl);

在你的控制器,你的单元测试现在可以

in your controller, your Unit Test can now


  • 验证返回值的类型是RedirectResult

  • 看那个正在通过检查result.Url它转换为RedirectResult
  • 后重定向到URL
  • 所有无需旋转起来IIS或试图clevery截取的Response.Redirect调用

  • 在一天结束的时候,RedirectResult调用的Response.Redirect在它的功能的ExecuteReuslt,但你的控制器单元测试坐在前面那个

  • Verify that the return value is of Type "RedirectResult"
  • Look at the URL that is being redirected to by checking result.Url after casting it to RedirectResult
  • All without having to spin up IIS or trying to "clevery" intercept the Response.Redirect call
  • At the end of the day, RedirectResult calls Response.Redirect in it's ExecuteResult function, but your Controller Unit Test sits in front of that

附录2:的虽然我在这,这里是一个自定义的ActionResult的例子:

Addendum 2: And while I am on it, here is an example of a Custom ActionResult:

<一个href=\"http://www.stum.de/2008/10/22/permanentredirectresult/\">http://www.stum.de/2008/10/22/permanentredirectresult/

这是只是为了显示自己不是黑魔法。他们实际上是pretty简单:你的控制器返回的操作结果,以及MVC运行时将最终调用的Ex​​ecuteReuslt功能就可以了,传入您的ActionResult可交互的ControllerContext。整点又是M-V-C的部分分开,使code可重复使用,并且使单元测试更容易,简称:举个很干净的框架

This is just to show that they are not "Black Magic". They are actually pretty simple: Your Controller returns an Action Result, and the MVC Runtime will eventually call the ExecuteResult function on it, passing in a ControllerContext that your ActionResult can interact with. The whole point again is to separate the parts of M-V-C, to make Code Reusable, and to make Unit testing easier, or in short: To give a very clean Framework.

这篇关于什么是ActionResult的返回类型的呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆