Simplifying ASP.NET Core s Program cs A Beginner s Guide
In the world of ASP.NET Core development, the Program.cs
file is like the control center of your application. It's where you configure everything that your web app needs to run smoothly. Let's take a closer look at what Program.cs
is and how you can use it to set up your ASP.NET Core application.
What is Program.cs?
Think of Program.cs
as the starting point of your ASP.NET Core application. It's where you define how your app should be built and configured before it starts serving requests from users. Inside Program.cs
, you'll find code that sets up things like services, database connections, API versioning, authentication, and more.
Configuring Services
One of the most important tasks in Program.cs
is configuring the services that your app needs. These services could be anything from database access to logging utilities. Here's a simple example of how you can configure a service:
// Configuring Services
builder.Services.AddScoped<IAuthService, AuthService>();
Health Checks
Health checks are like routine check-ups for your application. They help you monitor the health of your app's components and dependencies. Here's how you can set up health checks in Program.cs
:
// Health Checks
builder.Services.AddHealthChecks()
.AddSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"), tags: new[] { "database" });
CORS Policies
CORS (Cross-Origin Resource Sharing) policies control which external domains can access your API. You can configure CORS policies in Program.cs
like this:
// CORS Policies
var myCorsPolicy = "MyCorsPolicy";
builder.Services.AddCors(options =>
{
options.AddPolicy(myCorsPolicy, builder =>
{
builder.AllowAnyOrigin().WithExposedHeaders("x-my-custom-header");
});
});
Database Connections
Connecting your ASP.NET Core app to a database is essential for storing and retrieving data. Here's how you can set up database connections in Program.cs
:
// Database Connections
builder.Services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnectionPS"));
});
API Versioning
API versioning allows you to manage changes to your API over time. You can configure API versioning in Program.cs
like this:
// API Versioning
builder.Services.AddApiVersioning(o =>
{
o.AssumeDefaultVersionWhenUnspecified = true;
o.DefaultApiVersion = new ApiVersion(2, 0);
o.ReportApiVersions = true;
});
Swagger for API Documentation
Swagger generates interactive API documentation for your ASP.NET Core app. Here's how you can set up Swagger in Program.cs
:
// Swagger for API Documentation
builder.Services.AddSwaggerGen();
Harnessing the Power of MassTransit for Messaging
MassTransit is a powerful messaging library for .NET applications. You can configure MassTransit in Program.cs
like this:
// MassTransit Setup
builder.Services.AddMassTransit(x =>
{
x.UsingRabbitMq();
});
builder.Services.AddMassTransitHostedService();
Authentication and Authorization
Authentication and authorization control access to your app's resources. Here's how you can set up authentication and authorization in Program.cs
:
// Authentication and Authorization
builder.Services.AddJwtAuthentication();
builder.AddAppAuthentication();
builder.Services.AddAuthorization();
Configuring Logging
Logging helps you keep track of what's happening in your application. Configure logging in Program.cs
like this:
// Configuring Logging
builder.Host.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
});
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);
Enlisting Hosted Services for Background Tasks
Hosted services allow you to run background tasks in your ASP.NET Core app. You can enlist hosted services in Program.cs
like this:
// Enlisting Hosted Services for Background Tasks
builder.Services.AddHostedService<MyBackgroundService>();
builder.Services.AddHostedService<CartCleanupService>();
API Key Validation in ASP.NET Core's Program.cs
API key validation helps you control access to your API endpoints. You can set up API key validation in Program.cs
like this:
// API Key Validation
app.UseMiddleware<ApiKeyMiddleware>();
AutoMapper Configuration
AutoMapper simplifies object-to-object mapping in your ASP.NET Core app. Configure AutoMapper in Program.cs
like this:
// AutoMapper Configuration
IMapper mapper = MappingConfig.RegisterMaps().CreateMapper();
builder.Services.AddSingleton(mapper);
public static MapperConfiguration RegisterMaps()
{
var mappingConfig = new MapperConfiguration(config =>
{
config.CreateMap<LocationDto, Location>().ReverseMap();
});
return mappingConfig;
}
Ocelot Configuration
Ocelot is a library for building API gateways on ASP.NET Core. You can configure Ocelot in Program.cs
like this:
// Ocelot Configuration
builder.Configuration.AddOcelotWithSwaggerSupport(options =>
{
options.Folder = "OcelotConfiguration";
});
builder.Services.AddOcelot(builder.Configuration).AddAppConfiguration();
builder.Services.AddSwaggerForOcelot(builder.Configuration);
Rate Limiting
Rate limiting helps you control the rate of requests to your API endpoints. You can set up rate limiting in Program.cs
like this:
// Rate Limiting
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.addfixedwindowlimiter("fixed", options =>
{
options.permitlimit = 100;
options.window = timespan.fromseconds(60);
options.queueprocessingorder = queueprocessingorder.oldestfirst;
options.queuelimit = 5;
});
options.AddTokenBucketLimiter("token", options =>
{
options.TokenLimit = 100;
options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
options.QueueLimit = 5;
options.ReplenishmentPeriod = TimeSpan.FromSeconds(60);
options.TokensPerPeriod = 20;
options.AutoReplenishment = true;
});
options.AddPolicy("fixed-by-ip", httpContext =>
RateLimitPartition.GetFixedWindowLimiter(
httpContext.Request.Headers["X-Forwarded-For"].ToString(),
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 10,
Window = TimeSpan.FromMinutes(1)
}
)
);
options.AddConcurrencyLimiter("concurrency", options =>
{
options.PermitLimit = 10;
options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
options.QueueLimit = 5;
});
});
Conclusion
The Program.cs
file in ASP.NET Core 8 is the heart of your application’s configuration. From setting up databases to API versioning, authentication, messaging, and more, this file defines how your app behaves and scales. With real-world examples, you can see how each of these features applies to building a robust application, like an e-commerce site. Mastering the configurations in Program.cs
will help you build more efficient, scalable, and secure applications in ASP.NET Core.
Praful's Newsletter 🚀
Join 3900+ Engineers to Level Up Your Skills!
Subscribe to my Software Engineering Deep Dive Series covering ReactJS, Redux, ASP.NET Core, and Clean Architecture. Get 1 insightful email each week to enhance your development journey.