6

I got simple web service application:

public class MyController : Controller
{
  public ActionResult balance( int amount)
  {
  return Proceed(a.Balance( amount));
  }
}

Just wondering why type ActionResult is used as result. How user can use such type? Why I can't use just simple string?

vico
  • 17,051
  • 45
  • 159
  • 315
  • If you want to return string content, see this question http://stackoverflow.com/questions/553936/in-mvc-how-do-i-return-a-string-result Other than that, the question is too broad and does not have a specific problem for us to solve, can you narrow it down? – Esko Apr 28 '17 at 12:00
  • Because that's how it works? Sure, they could have written it differently but they didn't. to be more precise the ActionResult is later executed to give the actual returned content in a generic sort of context. If it allowed you to return strings or other things that aren't ActionResults then they'd need to special case every single possible return type they'd want to allow. – Chris Apr 28 '17 at 12:16
  • Is this Asp.Net or Asp.Net Core? Please add one of these tags to provide better context for your question. – RonC Apr 28 '17 at 12:25

2 Answers2

7

You use ActionResult if there are multiple return types possible deriving from ActionResult, like ViewResult, FileResult, JsonResult, etc.

For example, what if you have a method that gives back some content. One time you might want to load it from memory and return it as JSON (JsonResult). The next time it is called you have to load the JSON from your file system where FileResult might come in handy.

You can use a string too as a return type, or if you want to provide the Content-Type you can use return Content("Your string").

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 1
    But the question is: why I cannot just do `public string Balance` instead? – Evk Apr 28 '17 at 12:08
  • *How user can use such type?* was asked too. – Patrick Hofman Apr 28 '17 at 12:08
  • Flexibility - you need your result to be derived from the ActionResult type. How can you use it? Well, depends on your tasks. The action result may have fields like type, content, isError flag etc. The consumer method can easily distinct what is the result of the call and proceed in fashioned manner. – mihail Apr 28 '17 at 14:51
  • @mihail so `ActionResult` is anything you may need as a result for your controller to use. Right?https://imgur.com/TFMUfHY I'm really new at C#, so probably my question is not a good one. – carloswm85 Jul 16 '21 at 14:25
4

One reason why is that the action result contains two important pieces of the result, not just one. It contains the status code to return and it contains the body content to return. Additionally, it may also contain http headers to return. That's one reason your action method needs to return an ActionResult object rather than just a string.

RonC
  • 31,330
  • 19
  • 94
  • 139