Reputation: 885
I'm currently working on an ASP.NET Core 2 application. I configure my middleware in the Startup.cs
Configure method. In this Method - Configure - I'm setting my conventional routes as well. (I don't need Attribute routing in my application).
The problem is, as soon as the application is going to grow, the configuration might become a little bit confusing due to the huge amount of code.
Now I try to figure out, how to load the conventional routing table from an external class.
My current routing table looks very regular like that:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Now I try to figure out, how to load my routes from another class:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseMvc(routes =>
{
// .. I want to load my conventional routes from an external class
});
}
I just figured there is a way to create an extension method using the RouteBuilder class, like in this post:
How to write a middleware as custom router in asp.net core?
Hence, in my Configure method I could simply call something like that:
app.UseMyCoolRouter();
My problem is, I don't really know how to configre the RouteHandler to process regular requests:
var rh = new RouteHandler(context =>
{
// ... how to configure for regular routes?
});
var rb = new RouteBuilder(app, rh);
rb.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
app.UseRouter(rb.Build());
When I create the RouteBuilder instance without a RouteHandler:
var rb = new RouteBuilder(app);
I'm only getting an Null reference exception:
"A default handler must be set on the IRouteBuilder."
Do you know how I can load my routing table from another class or extension method into my Configure Method in Startup.cs?
Thank you very much!!
Upvotes: 0
Views: 802
Reputation: 885
Here is my solution:
public class Startup
{
//...
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDemoRoutes();
}
}
public static class ApplicationExtensions
{
public static IApplicationBuilder UseDemoRoutes(this IApplicationBuilder app)
{
app.UseMvc(routes => new DemoRouter(routes));
return app;
}
}
public class DemoRouter
{
public DemoRouter(IRouteBuilder routes)
{
ConfigureRoutes(routes);
// ConfigureMoreRoutes(routes);
}
private void ConfigureRoutes(IRouteBuilder routes)
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
}
}
First I created an extension method clean up the Configure method, next I call a class to configure all my routes.
I don't know if it's the best solution, but it works fine... What do you think? Thanks :)
Upvotes: 1