Being new to ASP.NET MVC, I've been wondering about the signature of Controller methods. In all the examples I've seen, they always seem to return ActionResult, even if they actually return a ViewResult instance or similar.
Here's a commonly seen example:
public ActionResult Index()
{
return this.View();
}
In such a case, wouldn't it make more sense to declare the method as public ViewResult Index()
, and get stronger type support?
Experimentation indicates that this works, so it seems possible.
I do realize that there may be situations where the polymorphism is desired (e.g. if you want to redirect only in certain situations, but show a view in other situations), but if the method always returns a view, I'd find a ViewResult more desirable.
In terms of future compatibility, ActionResult obviously provides a more robust signature, but if one controls the entire code base, it's always possible to change a method's signature to a more general return type if that should become necessary in the future.
Are the any other considerations that I'm not aware of, or should I just go ahead and declare my controller methods with specific return types?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…