//Another way; minimal, but organize routes externally with extension method;
//For larger applications, it's a good practice to organize your routes and other logic into separate files. In ASP.NET Core, you can achieve this by using extension methods to define routes in different files. Here's an example to illustrate how you can split routes into separate files:
-
Create an extension method for your routes:
First, create a new static class to hold your route definitions. For example, create a file named
WeatherForecastEndpoints.cs
:public static class WeatherForecastEndpoints { public static void MapWeatherForecastEndpoints(this IEndpointRouteBuilder endpoints) { endpoints.MapGet("/weatherforecast", () => { var forecast = new[] { new WeatherForecast(DateTime.Now, "Sunny", 25), new WeatherForecast(DateTime.Now.AddDays(1), "Cloudy", 22), new WeatherForecast(DateTime.Now.AddDays(2), "Rainy", 18) }; return forecast; }); } } public record WeatherForecast(DateTime Date, string Summary, int TemperatureC);
-
Use the extension method in your
Program.cs
file:In your
Program.cs
file, call the extension method to map the routes:var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapWeatherForecastEndpoints(); app.Run();
By organizing your routes into separate files, you can keep your Program.cs
file clean and maintainable.
This approach also makes it easier to manage and scale your application as it grows.