基本上,我有一个很大的社区名称列表,我需要为其创建路由。而不是为每个人创建一个新的路线:
routes.MapRoute(
"CommunityAirdrieMeadows",
"airdrie-communities-airdrie-meadows",
new { controller = "Search", action = "Index", community = "Airdrie Meadows" }
;
我希望能够通过列表进行预告并以这种方式创建它们。我遇到了Startup.cs包含.NET Core中的路由配置的问题。我只是好奇是否有一个很好的方法来引入我可以使用的项目列表,或者我是否以错误的方式解决这个问题。
答案 0 :(得分:1)
您可以通过IServiceProvider
访问IApplicationBuilder.ApplicationServices
。
E.g:
public void Configure(IApplicationBuilder builder)
{
[...]
builder.UseMvc(routes => MapRoutesFromDb(builder.ApplicationServices, routes));
}
private void MapRoutesFromDb(IServiceProvider services, IRouteBuilder routes)
{
var communityRepository = services.GetRequiredService<ICommunityRepository>();
var communities = communityRepository.GetAll();
// Get these from the database.
var communities = new []
{
new
{
Name="Airdrie Meadows",
Template="airdrie-communities-airdrie-meadows"
}
};
foreach (var community in communities)
{
routes.MapRoute($"Community {community.Name}", community.Template, new
{
controller = "Search",
action = "Index",
community = community.Name
});
}
}