Polymorphism in action methods MVC
I have two actions:
//Action 1 public FileResult Download(string folder, string fileName) { ... }
//Action 2 public FileResult Download(int id, string fileName) { ... }
When I try to download the following URL: http://localhost:54630/Downloads/Download/15?fileName=sharedhostinggsg.pdf
The error happens: The current request for action 'Download' on controller type 'DownloadsController' is ambiguous between the following action methods: System.Web.Mvc.FileResult Download(Int32) on type SextaIgreja.Web.Controllers.DownloadsController System.Web.Mvc.FileResult Download(System.String, System.String) on type SextaIgreja.Web.Controllers.DownloadsController
How can I make them:
Url: ../Downloads/Download/15?fileName=sha开发者_C百科redhostinggsg.pdf Action: Action 2
Url: ../Downloads?folder=Documentos$fileName=xx.docx Action: Action 1
I tried to put a constraint on my route, but did not work:
routes.MapRoute(
"Download", // Route name
"Downloads/Download/{id}", // URL with parameters
new { controller = "Downloads", action = "Download" }, // Parameter defaults
new { id = @"\d+" }
);
Searching the Internet I found several links but I could not understand how I can solve my problem. This, for example, the RequireRequestValue attribute is not found. I do not know which namespace it is.
The RequireRequestValue that you mention is a custom class they created (from Example posted)so you will not find it in any Microsoft namespace.
The class you will see inherits from ActionMethodSelectorAttribute. This attribute class can be used to help filter actions much like the AcceptVerbs attribute. So as in the example of that link they are returning true or false dependant on if a value is specified in the route arguments.
So following from that example you posted, create a class called RequireRequestValueAttribute. Then decorate your two Downloads action methods like so:
[RequireRequestValue("id")]
public FileResult Download(int id, string fileName) { ... }
[RequireRequestValue("folder")]
public FileResult Download(string folder, string fileName) { ... }
精彩评论