Asp – Is it good practice to explicitly specify the type of ActionResult returned by a controller in ASP.NET MVC

asp.net-mvc

I've been using ASP.NET MVC for a little while now and seem to find myself constantly returning things other than ActionResult from my controllers. I obviously return ViewResults but also JSonResults and also a couple of custom results that we've built in house.

I'm wondering tho, if, instead of declaring my controller methods like:

public ActionResult Index()

I should start declaring them as

public ViewResult Index()

or

public JsonResult Search()

if I always know that the Index action on my controller will always return a ViewResult or the Search action on my controller will always return a JsonResult?

EDIT: Just to clarify, I'm talking specifically about situations where I will always want a specific type of ActionResult to be returned.

Best Answer

I vote yes for two reasons.

  1. You are explicitly declaring what you expect the method to return and the compiler will catch any attempt to do otherwise. No need for a unit test that does a Assert( result is ViewResult).

  2. You have to cast the result to the expected type in your tests when examining any properties unique to that result type (For example, checking Url property of the RedirectResult). Simply declaring the test variable as var removes any brittleness incurred by changing types.