Table of content
Where to define Routing
Attribute Routing
Static Routing
How to a URL matches an action
Convention-Based URL Routing
Dynamic Routing:map a route pattern to a dynamic route handler
Where to define Routing
Static Routing
Demo:https://www.iaspnetcore.com/robots.txt
step 1. Routing to controller actions
// contact us
endpoints.MapControllerRoute("ContactUs",
"contact-us",
new { controller = "Page", action = "ContactUs" });
// pages
endpoints.MapControllerRoute("Page",
"{sename}",
new { controller = "Page", action = "Detail" });
// for dynamic pages
endpoints.MapDynamicControllerRoute<PageRouteTransformer>("{sename}");
step 2: move to a class
namespace Microsoft.AspNetCore.Builder
{
public static class RegisterRoutes3
{
/// <summary>
/// 注册静态路由
/// </summary>
/// <param name="routes"></param>
public static void MapModuleRoute3(this IEndpointRouteBuilder endpointRouteBuilder)
{
//endpointRouteBuilder.MapControllerRoute(name, pattern,
// new { controller = "Topic", action = "TopicDetails" });
//robots.txt
endpointRouteBuilder.MapControllerRoute("robots.txt", "robots.txt",
new { controller = "Common", action = "RobotsTextFile" });
}
}
}
Step 3:Add to route table
app.UseEndpoints(endpoints =>
{
var pattern = "{SeName}";
endpoints.MapDynamicControllerRoute<SlugRouteTransformer>(pattern);
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(name: "mobile-page-html5",
pattern: "mobile-page-html5",
defaults: new { controller = "MobileHtml5", action = "index" });
endpoints.MapControllerRoute(name: "mobile-page-bootstrap",
pattern: "mobile-page-bootstrap",
defaults: new { controller = "MobileBootstrap5", action = "index" });
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area}/{controller}/{did?}/{action=Index}/{id?}");
endpoints.MapModuleRoute3(); //static Routing
});
Attribute Routing
public class MobileBootstrap5Controller : Controller
{
// GET: MobleBootstrap5Controller
public ActionResult Index()
{
return View();
}
[Route("mobile-page-bootstrap-step1")]
public ActionResult IndexStep1()
{
return View();
}
[Route("mobile-page-bootstrap-step2")]
public ActionResult IndexStep2()
{
return View();
}
[Route("mobile-page-bootstrap-step3")]
public ActionResult IndexStep3()
{
return View();
}
[Route("mobile-page-bootstrap-step4")]
public ActionResult IndexStep4()
{
return View();
}