I have an ASP.NET Core 3.1 MVC router question.
When I change index route to [Route("Index")]
in HomeController
enter image description here , and then enter the url localhost:5000/index
in web browser, it works!
But in my ASP.NET Core MVC project, the default startup url is localhost:5000/home/index
enter image description here .
Question
How can I change the default startup url to localhost:5000/index
?
I wish use localhost:5000/home/login
to visit the login function in the HomeController
.
Add following route before your default route.
endpoints.MapControllerRoute(
name: "customindex",
pattern: "index",
defaults: new { controller="Home", action="Index"});
});
pattern can support default value but it works with common scenario like controller/action but if you want specific pattern then you have to specify pattern and also set defaults so those will supply as route value in order to identify action to call.
Define the following default
route:
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
Then apply route attributes in the Home
controller:
[Route("")]
[Route("{id:int}")]
[Route("Index")]
[Route("Index/{id:int?}")]
[Route("Home/{id:int?}", Order = 5)]
[Route("Home/Index/{id:int?}", Order = 6)]
public IActionResult Index(int? id)
{
return View((object)id);
}
[Route("Home/Login")]
[Route("Login")]
public IActionResult Login()
{
return View();
}
If you really need to display the localhost:5000/index
URL when user entering the localhost:5000/
fix the Index
action method to use the RedirectToAction()
:
[Route("")]
[Route("{id:int}")]
[Route("Index")]
[Route("Index/{id:int?}")]
[Route("Home/{id:int?}", Order = 5)]
[Route("Home/Index/{id:int?}", Order = 6)]
public IActionResult Index(int? id)
{
var path = HttpContext.Request.Path;
if (path.HasValue && path.Value == "/")
{
return RedirectToAction("Index", new { id = id});
}
return View((object)id);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.