MVC Website from .NET Core Empty Project
We will going to create a simple MVC web application from the empty template provided by visual studio.
Open visual studio and select ASP.NET Core Empty template for creating the application and click on next.
After selecting the default suggestion the code in program.cs will look like this.
Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
When we run the application, it will display “Hello World!” in the browser.
Now, add a controller in the Controllers folder and create a view for it.
Add the following code in the Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMvc();
var app = builder.Build();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}",
defaults: new { controller = "Home", action = "Index" });
app.MapGet("/", () => "Hello World!");
app.Run();
Then, run the application and type “Product/Index” in the url followed by “http{s}://localhost:{portnumber}/Product/Index”
builder.Services.AddMvc()
This will add MVC services to the service collection. If we go deep into this method by checking the github code, we can check how it’s adding controller services, view services, razor services etc. So, basically we will have all the setup required to run our application with controller, views or razor pages.
app.UseRouting()
This will add route matching middleware in the request pipeline. It will match the route entered in the URL with the set of endpoints defined in the application, and select the best match.
app.MapControllerRoute()
This adds controller’s action method as endpoints. Once the route will be matched, action method will be executed.