ContentResult vs. string

Tobias picture Tobias · Aug 28, 2013 · Viewed 52.2k times · Source

I recently was asked why to use ContentResult instead of returning string. Unfortunately I could not give a better answer than: "It is best practice."

Does anyone have a better answer?

To better understand the question. What's the difference?

public ActionResult Foo(){
    return Content("Some string");
}

public string Bar(){
    return "Some string";
}

Answer

Steve Ruble picture Steve Ruble · Aug 28, 2013

If you return something other than an ActionResult the default behavior is to create a ContentResult wrapping the result of calling ToString() on whatever you did return (or EmptyResult if you returned null). Reasons I can think of to explicitly return ContentResult:

  • It reinforces the fact that the method is an action, rather than a regular method, so devs are less likely to make mistakes like casually renaming it.
  • If in the future you need to specify the content-type you won't need to change the method signature.
  • It doesn't hide the ToString() call. This doesn't matter if you're returning string, but returning a complex type could have unexpected results.