ASP.NET Core 2: What’s new in Routes?

The beloved Routes are still with us in ASP.NET Core, however there have been some additional changes made to the routing syntax which might make your routes a bit easier to enter and to manage.

Default Values:

Setting a default value can now be done in the definition rather than in the defaults parameter, though that is still supported. In this example “Sales” is the default controller and “Index” the action.

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

Optional Values

We can now indicate that a value is optional via the {id?} syntax.

{controller=Sales}/{action=Index}/{id?}

Defining Type

In this example the id must be a int

.../{id:int}

Wild Cards

Think of a wild card as a kind of universal Catch All

routes.MapRoute( name: "default", 
template: "{controller=Sales}/{action=Index}/{id:int}/{*more}");

This would catch /any/url/999/a/b/c and /any/url/999

 Areas

Areas in MVC 6 are very similar to Areas in MVC 5, but that topic will be covered more in depth in another article.

For now, you’ll need to add {area:exists} as a route param to allow for proper routing. “Exists” simply applies a KnownRouteValueConstraint (see here)

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s