Creating an MVC Project
Create an ASP.NET Core MVC project, run it in the browser, and find your way around its folders and Program.cs.
Apprentice · ASP.NET Core · C# · Updated
After this lesson you can
- Create an ASP.NET Core MVC project and run it in the browser
- Find your way around an MVC project's folders, Program.cs and appsettings.json
Key takeaways
dotnet new mvc -n NorthwindWebcreates an MVC project, anddotnet runstarts it on the address it prints. Ctrl+C stops it.- The
Controllers,ModelsandViewsfolders hold the three parts of MVC, andwwwrootholds static files sent as they are. Program.csbuilds and starts the app:AddControllersWithViews()turns on MVC, andMapControllerRoutesets the route.- ASP.NET Core reads
appsettings.jsonfor you, so the connection string goes in itsConnectionStringssection.
Time to make a web app. In this chapter you'll build NorthwindWeb, a small website for the Northwind products you've been querying, one piece per lesson.
Create the project
From the terminal:
cd ~/bootcamp
dotnet new mvc -n NorthwindWeb
cd NorthwindWeb
dotnet run
Or in Visual Studio: File > New > Project, choose ASP.NET Core Web App (Model-View-Controller), name it NorthwindWeb, and keep the defaults (.NET 10, Authentication type: None).
dotnet run builds the app and starts it. It prints the address it's listening on, then waits for requests:
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5204
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
Open that address in your browser (your port number will be different), and there's your website: a Welcome page with Home and Privacy links. Press Ctrl+C in the terminal to stop it. In Visual Studio, Ctrl+F5 runs the app and opens the browser for you.
If the browser warns that the connection isn't private on an https://localhost address, trust the development certificate once, then restart the app:
dotnet dev-certs https --trust
What's in the project
NorthwindWeb/
├── Controllers/ HomeController.cs: answers requests
├── Models/ classes that carry data
├── Views/ .cshtml files that become HTML
│ ├── Home/ Index.cshtml and Privacy.cshtml, the views for HomeController
│ └── Shared/ _Layout.cshtml, the frame around every page
├── wwwroot/ static files sent as they are: css, js, images, and Bootstrap in lib/
├── Properties/ launchSettings.json: the app's port
├── appsettings.json the app's settings, such as connection strings
├── Program.cs starts the app
└── NorthwindWeb.csproj
Controllers, Models and Views: the three folders are the three parts of the MVC pattern, the subject of the next lesson.
Program.cs
Program.cs builds the app and starts it. The template's version, with its comments trimmed:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapStaticAssets();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.WithStaticAssets();
app.Run();
You don't need every line yet. These are the ones that matter now:
| Line | What it does |
|---|---|
AddControllersWithViews() |
Turns on MVC: controllers and views |
MapStaticAssets() |
Sends the files in wwwroot as they are |
MapControllerRoute(...) |
The route: how an address picks a controller. More in Controllers and Actions |
app.Run() |
Starts listening, and keeps going until you stop it |
(The template writes var for the builder and the app. Their full types are long, WebApplicationBuilder and WebApplication, and var lets C# work them out.)
appsettings.json
ASP.NET Core reads appsettings.json for you when it starts. Add NorthwindWeb's connection string, in the same ConnectionStrings section you used in Configure the Project for SQL Server:
{
"ConnectionStrings": {
"Northwind": "Server=localhost;Database=Northwind;Integrated Security=true;TrustServerCertificate=true;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
And add the SQL Server driver, as before:
dotnet add package Microsoft.Data.SqlClient
dotnet add package System.Security.Cryptography.Pkcs
A web project copies appsettings.json next to the program by itself, so there's no CopyToOutputDirectory setting to add this time.
Common problems
| What you see | What to do |
|---|---|
Failed to bind to address http://127.0.0.1:5204: address already in use |
The app is already running, maybe in another terminal or in Visual Studio. Stop that one first. |
| The browser says the connection isn't private | Run dotnet dev-certs https --trust once, then restart the app. |
| Changes to a view don't show | Stop the app and run it again, or use dotnet watch, which restarts it whenever you save. |
Check yourself
2 questions to try on the lesson page.
So what
One command gives you a working website with a home page, a layout, Bootstrap and a route. From here on, every feature is a controller, a model or a view added to this same project.
Key terms
- Program.cs
- Static Files