ASP.Net MVC Action method override
Does the controllers allow overridden action methods?
For example:
Can I have two me开发者_Go百科thods like:ActionResult SendResults() { ... }
FileContentResult SendResults() { ... }
C# impossible, Asp.net MVC action methods possible
If you can distinguish controller action methods by anything that an action method selector can separate, then it's possible to have two controller actions with the same name but with a different result:
[HttpGet]
[ActionName("SendResults")]
ActionResult SendResultsGet() { ... }
[HttpPost]
[ActionName("SendResults")]
FileContentResult SendResultsPost() { ... }
The main idea here is that you can use the ActionNameAttribute to name several action methods with the same name. Based on other action method selector attributes on these actions either of them will be executed.
When there are no out-of-the-box action method selectors that you can use you can always write your own custom one that solves your problem.
I've written two blog posts about action method selectors that may be of interest to you:
- Improving Asp.net MVC maintainability and RESTful conformance
- Custom action method selector attributes in Asp.net MVC
You can never have two methods only differing by return types in .Net. How would the code know which one to pick?
Consider the following code:
ActionResult result = SendResults();
It is impossible from that code to tell which method you want to invoke as FileContentResult is derived from ActionResult. You will have to do something like:
ActionResult result = SendFileContentResults();
C# bases it's signature based on the method name and parameters. To be able to create another method you have to have another signature and as the return type is not in the signature you have to change either the name or the parameters to make it compile.
- To override - methods need to have same return types.
- To overload - methods need to have different signatures.
If you need to return different result based on some condition, you could do something like this:
public ActionResult SendResults()
{
if (somecondition)
{
return View();
}
else
{
return File("readme.txt", "text");
}
}
精彩评论