I recently was asked why to use ContentResult instead of returning string. Unfortunatly I could not give a better answer than: "It is best practice."
Does anyone have a better answer?
Update: To better understand the question. What's the difference?
public ActionResult Foo(){
return Content("Some string");
}
public string Bar(){
return "Some string";
}
If you return something other than an
ActionResult
the default behavior is to create aContentResult
wrapping the result of callingToString()
on whatever you did return (orEmptyResult
if you returnednull
. Reasons I can think of to explicitly returnContentResult
:ToString()
call. This doesn't matter if you're returningstring
, but returning a complex type could have unexpected results.Two main advantages:
ContentEncoding
propertyContentType
propertyAlso, if you want to be OO-clean about it,
ContentResult
, along with allActionResult
derived classes follow the Command Pattern by providing anExecuteResult
command for the MVC pipeline to run.One difference as i know is :
Content return result without quotations marks if you want.
String return result in Quotations marks all the time.
You can't return a string on a method which returns an ActionResult, so this is when you could use a ContentResult to return a plain string like so:
ContentResult by default returns a type of
text/plain
. If you only ever needed to return a string, then you would use the method to return a stringReturning a ContentResult helps protect your application.
E.g If your application allows input from users, a malicious user might try to parse a javascript text. This will prevent javascript from executing in your application
One another difference is Content result can return different content's result. Like string, Html, JavaScript result etc.
But string return only the string result.