Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContentResult vs. string

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"; } 
like image 428
Tobias Avatar asked Aug 28 '13 07:08

Tobias


People also ask

What is ContentResult?

ContentResult represents a user-defined content type. It is inherited from ActionResult. ContentResult has the following three properties: Content that we want to render on browser. ContentEncoding that defines the encoding of the content.

How do I return an action string?

You can't return a string from a method which returns an ActionResult, so in this case you return Content("") as swilliams explained. If you only ever need to return a string, then you would have the method return a string, as Phil explained.


1 Answers

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.
like image 72
2 revs, 2 users 92% Avatar answered Oct 14 '22 13:10

2 revs, 2 users 92%