.net core custom routing with GET parameter

411 Views Asked by At

.Net Core MVC, assume a custom route something like this:

App.UseMvc(routes =>
{
  routes.MapRoute(
  name: "fantasyBoardArea",
  //constraints: "{area=FantasyDraftBoard}/{controller=Test}/{league?}/{id}",
                  template: "{area=FantasyDraftBoard}/{leagueName?}/{controller=Test}/{action=Index}/{search?}");
});

Is there some way to set it so that if the {leagueName} in the route above is one of 4 strings (NHL, NFL, NBA, MLB) then I want it to use the typical route (area/controller/action/(queryParamters), but ALSO use the leagueName as a route parameter on my controller? I don't mind the route URL looking like "domainname.com/FantasyDraftBoard/NHL/Controller/Action/". It would be nice if it would still hide "Index" when it is the Index action

ex:

[Area("FantasyDraftBoard")]
public class TestController : Controller
{      
    public async Task<IActionResult> Index(string leagueName, string search)
    {
       if(!String.IsNullOrEmpty(leagueName)
       {
           //do something
       }
       //Code removed, not important
    }

If the leagueName does not match one of those four strings then I want it to be ignored and treated as a regular controller/action route.

Note - Ignore the constraints in my route at the top, that was just for testing and trying things out.

Thoughts?

1

There are 1 best solutions below

0
On
  app.UseMvc(routes =>
        {
            routes.MapRoute(
                        "New",
                        "{area:exists}/{leagueName?}/{controller}/{action}/{id?}",
                        new { leagueName= "NHL", controller = "Default", action = "Index" },
                        new { leagueName= "NHL|NFL" }
                    );
            routes.MapRoute(
                name: "areaRoute",
                template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

   [Area("FantasyDraftBoard")]
   public class DefaultController : Controller
   {
    public IActionResult Index(string leagueName)
    {
        return View();
    }
   }

I verified that the leagueName is set to one of the values.

EDIT: If the value is not present then the leaguename is set to NULL but if it contains values other than those 4 then it returns 404