I want to change the route display name in URL, like below:
Access UserController
display: https://localhost:7214/admin/login
Access CustomerController
display: https://localhost:7214/customers/index
UserController.cs
[Route("admin")]
public class UserController : Controller
{
[AllowAnonymous]
public IActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
}
CustomerController.cs
[Route("customers")]
public class CustomerController : Controller
{
public IActionResult Index()
{
return View();
}
}
Program.cs
app.MapControllerRoute(
name: "default",
pattern: "{controller=Admin}/{action=Login}/{id?}");
app.Run();
But when I run the program, hit the following error:
I don't want to use Areas
, any other options other than Areas
?
Updated:
I modified code below in Program.cs
app.MapControllerRoute(
name: "customers",
pattern: "customers/{action}/{id?}",
defaults: new { controller = "Customer", action = "Index" });
Access index page is find, but access route method, hit error 404.
public class CustomerController : Controller
{
public IActionResult Index() <-- working fine
{
return View();
}
[Route("test/export")]
public IActionResult Test() <-- error 404
{
return View();
}
}
Routing from Contoller using Route attribute,
UserController:
[Route("admin/[action]/{id?}")]
public class UserController : Controller
{
[AllowAnonymous]
public IActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
}
CustomerController:
[Route("customers/[action]/{id?}")]
public class CustomerController : Controller
{
public IActionResult Index()
{
return View();
}
}
Or you can add route in Startup.cs (Program.cs file for 6.0 and up).
Multiple conventional routes:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(
name: "demo",
pattern: "admin/{action}/{id?}",
defaults: new { controller = "User", action = "Login" });
app.MapControllerRoute(
name: "demo2",
pattern: "customers/{action}/{id?}",
defaults: new { controller = "Customer", action = "Index" });
Reference: Asp.net core Docs https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0