I'm trying to add a route to the default one, so that I have both urls working:
http://www.mywebsite.com/users/create
http://www.mywebsite.com/users/1
This will make the first route work:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "users", action = "Index", id = UrlParameter.Optional } );
However, the second route won't work obviously.
This will make the second route work, but will break the first one:
routes.MapRoute( name: "Book", url: "books/{id}", defaults: new { controller = "users", action = "Details" } );
How to combine the two route configurations so that both URLs work? I apologize if there is already a question like this on SO, I wasn't able to find anything.
asp-route. The asp-route attribute is used for creating a URL linking directly to a named route. Using routing attributes, a route can be named as shown in the SpeakerController and used in its Evaluations action: C# Copy.
In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig. cs file is used to set routing for the application.
If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.
The key is to put more specific routes first. So put the "Book" route first. Edit I guess you also need a constraint to only allow numbers to match the "id" part of this route. End edit
routes.MapRoute( name: "Book", url: "books/{id}", defaults: new { controller = "users", action = "Details" }, constraints: new { id = @"\d+" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "users", action = "Index", id = UrlParameter.Optional } );
And ensure that the "id" parameter in your "Details" action is an int:
// "users" controller public ActionResult books(int id) { // ... }
This way, the "Books" route will not catch a URL like /users/create
(since the second parameter is reqiured to be a number), and so will fall through to the next ("Default") route.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With