Zack Antony Bucci
Zack Antony Bucci

Reputation: 601

How to add a URL attribute in MapRoutes in ASP.NET Core MVC

I have the following in a .NET Framework MVC VB Project within the RouteConfig in startup:

    routes.MapRoute(name:="RaceCardHome", url:="race-card", defaults:=New With {.controller = "Races", .action = "Index"})
    routes.MapRoute(name:="RaceCard", url:="race-card/{raceName}", defaults:=New With {.controller = "Races", .action = "Race"})

As you can see the there is a 'url' attribute to change the url so it's not just the {controller}.

How do I accomplish this on .NET Core 2.2 MVC as there doesn't seem to be a URL attribute like above.

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

            routes.MapRoute(
               name: "RaceCardHome",
               template: "{controller=Races}/{action=Index}");

            routes.MapRoute(
              name: "RaceCard",
              template: "{controller=Races}/{action=Race}");

        });

Upvotes: 0

Views: 264

Answers (1)

prinkpan
prinkpan

Reputation: 2247

I haven't tried it, but this should work.

app.UseMvc(routes =>
{
    routes.MapRoute(
       name: "RaceCardHome",
       template: "race-card",
       defaults: new {controller = "Races", action = "Index"});

    routes.MapRoute(
      name: "RaceCard",
      template: "race-card/{raceName}",
      defaults: new {controller = "Races", action = "Race"});

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

Also, a point to note is the route named "default" should always be at the end.

More details can be found here

Upvotes: 2

Related Questions