Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Last active April 2, 2025 00:23
Show Gist options
  • Save joe-oli/a33c24e3a8d2bafd5cc200a3276f81f6 to your computer and use it in GitHub Desktop.
Save joe-oli/a33c24e3a8d2bafd5cc200a3276f81f6 to your computer and use it in GitHub Desktop.
dotnet new webapi -n MyWebApiProj --use-program-main and --use-controllers

//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:

  1. 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);
  2. 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.

//--use-program-main only;
//Program.cs generates a Program Class with a Main method;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthorization();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseHttpsRedirection();
app.UseAuthorization();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", (HttpContext httpContext) =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = summaries[Random.Shared.Next(summaries.Length)]
})
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");
app.Run();
}
}
//By default, minimal: no Main method(), no Controllers;
//dotnet new webapi -n ProjName
//Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
//Older style, with Startup.cs; BEFORE .NET 6.x;
// Program.cs (Typical .NET Core 3.1)
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace MyWebApp
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
// Startup.cs (Typical .NET Core 3.1)
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyWebApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); // Or AddMvc(), depending on the type of application
// Example: Adding Entity Framework Core
// services.AddDbContext<ApplicationDbContext>(options =>
// options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// Example: Adding other services
// services.AddScoped<IMyService, MyService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error"); // Or a custom error page.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization(); // If you are using authentication and authorization
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // Or endpoints.MapRazorPages(), depending on the type of application.
//endpoints.MapGet("/", async context =>
//{
// await context.Response.WriteAsync("Hello World!");
//});
});
}
}
}
//dotnet new webapi -n ProjName --use-program-main --use-controllers
//Program.cs Main() method
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
//Controllers folder;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment