问题
What is the point of an action returning ActionResult?
回答1:
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:
If you do
return Redirect(newUrl);
in your controller, your Unit Test can now
- 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
Addendum 2: And while I am on it, here is an example of a Custom ActionResult:
http://www.stum.de/2008/10/22/permanentredirectresult/
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.
回答2:
Since it is the base class, it allows you to return any of the ActionResult subclasses, such as ViewResult or JsonResult. I typically return ViewResult as the default, but override that behavior if I am dealing with Ajax to return a JsonResult object.
This allows me to add Ajax as a progressive enhancement and keep the application working without JavaScript and without the need for separate controller actions.
回答3:
ActionResult is the base class for many different types of controller results. By returning the base class, the controller action can return different types of results depending on the outcome of the method -- a ViewResult, a RedirectToActionResult, etc. ActionResult contains all of the data needed by the View or new Action that is the result of the current controller action.
来源:https://stackoverflow.com/questions/289171/whats-the-point-of-actionresult-return-type