c# - How to set different routes for the same Controller method with different parameters? -
i have reportcontroller llooks this:
public iactionresult reportdetails(int? reportid){ .... }
and
public iactionresult reportdetails(int? reportid, bool ? approved) { .... }
and tried routing, bu failed. actual code written in startup.cs:
app.usemvc(routes => { routes.maproute( name: "reportdetailsvalidation", template: "descriptionvalidation", defaults: new { controller = "report", action = "reportdetails", reportid ="{reportid}", approved = "{approved}" } ); routes.maproute( name: "reportdetails", template: "description", defaults: new { controller = "report", action = "reportdetails"} ); routes.maproute( name: "default", template: "{controller=home}/{action=index}/{id?}"); });
as have seen need match following url's:
/report/reportdetails?reportid=7 first and
/report/reportdetails?reportid=7&approved=true second
you can't that, have 2 methods identical name different parameters, because should ambiguousactionexception.
asp core action selector not care action's parameters during select action. therefore can't have 2 actions correspond 1 route template. workaround play action constraints (like httpget , httppost). can check on github. (see selectbestcandidate method)
theoretically if parameters matters logic choose between actions based on parameters should in selectbestactions method, ignores parameters.
in case option seems to have 1 method:
public iactionresult reportdetails(int? reportid, bool? approved) { .... }
and check if approved null (/report/reportdetails?reportid=7), implement 1st logic, otherwise(/report/reportdetails?reportid=7&approved=true) implement 2nd logic. if logic contains many lines can extract them in new method , call it.
public iactionresult reportdetails(int? reportid, bool? approved) { if (approved != null) { //implement logic 2nd case(approved=true) } //implement logic 1st case (just reportid=7) }
Comments
Post a Comment