What's the point of ActionResult return type?

后端 未结 3 1130
臣服心动
臣服心动 2021-02-01 23:13

What is the point of an action returning ActionResult?

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-01 23:51

    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.

提交回复
热议问题