Improve routes

Asked

Viewed 58 times

0

Do people have a better way to do these routes? Or for every action in my Controller I’ll have to create your routing?

app.UseMvc(routes =>
        {
            routes.MapRoute(
               "Login",
               "Login",
               new { controller = "Usuario", action = "Login" }
               );
            routes.MapRoute(
               "registro",
               "Registro",
               new { controller = "Usuario", action = "Registro" }
               );

1 answer

1


When creating an ASP.NET Core MVC project, you will default to the following route:

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

Basically, she interprets it like this:

  • 1st Token: Controler: if not informed, use the controller Home;
  • 2nd Token: Action: if not informed, use the method Index;
  • 3rd Token: ID: if not informed, will not be sent (is optional). And will only be sent if the given method, in the 2nd token, has some parameter called "id";

This route model can supply the vast majority of routes on your site. You can even expand or add new generic routes.

If all your routes are similar, you can create only one using tokens (tokenizing) values that can be passed in the Route.

Analyzing the default route, the following routes will be supplied:

/Products/Details/5

Interpreted as follows::

{ controller = Products, action = Details, id = 5 }

Or just

/Products

Interpreted as follows::

{ controller = Products, action = Index}

More information you can find in the manual Routing to controller actions in ASP.NET Core

  • One more question, I switched to the "Attribute routing" scheme, do you think this is a good thing or do you not recommend doing the routes this way? https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.1#attribute-routing

  • 1

    Attribute routing allows you to leave the route next to the method that will be used and also allows greater precision. The use is fully valid. The important thing is to keep everything clean and concise.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.