Reputation: 119
I have a project in ASP.NET Core 5, what I need is quite simple. I want to indicate in the id
value a default int value in routing. However, when I trace the controller, it always returns the id as 0
or null
.
public IActionResult Seccion(int id)
{
return View();
}
this is my Start.up file
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=podcast}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "historias",
pattern: "seccion/{id=300}",
defaults: new { controller = "Podcast", action = "Seccion" });
});
As you can see, I expect when the https://localhost:xxx/podcast/seccion/historias
is entered the Seccion()
action method is called with id
set to 300
by default. But the id
always arrives 0
.
Upvotes: 6
Views: 1487
Reputation: 8915
Your problem caused by wrong routes registration order (conventional routing is order-dependent). It is important that you add "historias" route before the Default one. Routes are processed in the order they are listed. So, define routes in the following order:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "historias",
pattern: "{controller}/seccion/historias/{id=300}",
defaults: new { controller = "Podcast", action = "Seccion" });
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=podcast}/{action=Index}/{id?}");
});
And the "historias" route template does not include the controller name. Therefore it is necessary to use the following URL: https://localhost:port/seccion
or https://localhost:port/seccion/[some_number_here]
.
Pay attention! When you are using http://localhost:port/podcast/seccion
the "default" route template is engaged and therefore the id
is 0
.
But, if you will define the default id
value in the action method like public IActionResult Seccion(int id=300)
the following URL's https://localhost:port/podcast/seccion
or https://localhost:port/podcast/seccion/[some_number_here]
will properly work too.
For more information see Set up conventional route
Upvotes: 4
Reputation: 2910
You need to assign a value to the ID on the url, like this:
https://localhost:44394/podcast/seccion/300
For more related content, please refer to the official document:
Routing to controller actions in ASP.NET Core
Upvotes: 0
Reputation: 2252
Try like this:-
Your controller:-
[HttpGet]
[Route("[action]/{id}")
public IActionResult Seccion(int id)
{
return View();
}
when you call https://localhost:xxx/podcast/seccion/id
you will found your output as expected and your id is 300 by default. or you can use simply this for default id value:- public IActionResult Seccion(int id ?? 300)
Upvotes: 0
Reputation: 874
you should set your default value in Action
public IActionResult Seccion(int id = 300)
{
return View();
}
when call https://localhost:xxx/podcast/seccion
id
is 300
and when call https://localhost:xxx/podcast/seccion/1
id
is 1
for more information read this
Upvotes: 1