要使用ASP.NET Core的可配置化路由功能,可以按照以下步骤进行操作:
services.AddControllersWithViews().AddRazorRuntimeCompilation();
{
"Routes": [
{
"Path": "/",
"Controller": "Home",
"Action": "Index"
},
{
"Path": "/about",
"Controller": "Home",
"Action": "About"
},
{
"Path": "/contact",
"Controller": "Home",
"Action": "Contact"
}
]
}
app.UseEndpoints(endpoints =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("ConfigurableRoutes.json")
.Build();
var routes = configuration.GetSection("Routes").Get>();
foreach (var route in routes)
{
endpoints.MapControllerRoute(
name: route.Path.Trim('/'),
pattern: route.Path,
defaults: new { controller = route.Controller, action = route.Action });
}
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
public class Route
{
public string Path { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
}
这样,你就可以使用可配置化的路由规则来定义和管理你的应用程序的路由了。