Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • ASP.NET Core - Get Started
  • .NET Core Overview
  • ASP.NET Core Overview
  • Install .NET Core
  • Create ASP.NET Core MVC
  • Project Structure
  • wwwroot
  • Program.cs
  • Command-line Interface
  • Dependency Injection
  • Built-in IoC Container
  • Middleware
  • Add Custom Middleware
  • Configure Default File
  • Environment Variable
  • Exception Handling
  • Serving Static Files
  • Serving Static Files From Other Folder
  • Logging in .NET Core
  • Logging in ASP.NET Core
  • .NET Core Application Types
  • Code Sharing
  • Target Multiple Frameworks
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Program.cs in ASP.NET Core MVC

Program.cs file in ASP.NET Core MVC application is an entry point of an application. It contains logic to start the server and listen for the requests and also configure the application.

Every ASP.NET Core web applications starts like a console application then turn into web application. When you press F5 and run the application, it starts the executing code in the Program.cs file.

The following is the default Program.cs file created in Visual Studio for ASP.NET 7 (ASP.NET Core) MVC application.

Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Notice that there is no Main() method in the above Progrm.cs file because it uses top-level statements feature of C# 9.

The following is the simplified structure of program.cs that specifies the tasks you can perform at different places.

var builder = WebApplication.CreateBuilder(args);

// register services with the dependency injection container using builder object here

var app = builder.Build();

//configure middleware (request pipeline) using app object here

// Start the application
app.Run();

Let's understand program.cs code step-by-step:

The first line creates an object of WebApplicationBuilder with preconfigured defaults using the CreateBuilder() method.

var builder = WebApplication.CreateBuilder(args);

The CreateBuilder() method setup the internal web server which is Kestrel. It also specifies the content root and read application settings file appsettings.json.

Using this builder object, you can configure various things for your web application, such as dependency injection, middleware, and hosting environment. You can pass additional configurations at runtime based on the runtime parameters.

The builder object has the Services() method which can be used to add services to the dependency injection container.

builder.Services.AddControllersWithViews();

The AddControllersWithViews() is an extension method that register types needed for MVC application (model, view, controller) to the dependency injection. It includes all the necessary services and configurations for MVC So that your application can use MVC architecture.

var app = builder.Build();

The builder.Build() method returns the object of WebApplication using which you can configure the request pipeline using middleware and hosting environment that manages the execution of your web application.

Now, using this WebApplication object app, you can configure an application based on the environment it runs on e.g. development, staging or production. The following adds the middleware that will catch the exceptions, logs them, and reset and execute the request path to '"/home/error" if the application runs on the development environment.

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}

Note that the method starts with "Use" word means it configures the middleware. The following configures the static files, routing, and authorization middleware respectively.

app.UseStaticFiles();

app.UseRouting();
app.UseAuthorization();

The UseStaticFiles() method configures the middleware that returns the static files from the wwwroot folder only.

The MapControllerRoute() defines the default route pattern that specifies which controller, action, and optional route parameters should be used to handle incoming requests.

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

Finally, app.run() method runs the application,start listening the incomming request. It turns a console application into an MVC application based on the provided configuration.

So, program.cs contains codes that sets up all necessary infrastructure for your application.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.