ASP.NET Core Tutorial
Tags: webdev, tutorial, dotnet, csharp
Published: 2021-03-22 19:08:49

`ASP.NET` is the web app building tool for Microsoft's .NET Core platform. It is used extensively for enterprise or cloud-enabled applications and is suitable for MVC full-stack or back-end development.

Following the growing popularity of cloud computing and scalable web apps, .NET has been steadily rising in demand. More companies are interested in the unique combination of cross-platform and scalable technology, resulting in more job opportunities for .NET developers. 

Today, we'll help you get started with `ASP.NET` Core by exploring its MVC structure and help you through your first `ASP.NET` Core web application!

<br>

**Here’s what we’ll cover today:**
 
* [What is .NET Core](#what)
* [ASP.NET MVC Project Structure](#structure)
* [Non-MVC Architectures](#non-mvc)
* [Hello World: how to create an ASP.NET Core web app](#)
* [Advanced concepts to learn next](#next)

<br>

<h4><b> Learn full-stack .NET Core in half the time</b></h4>
 
Get hands-on practice with all the most tested concepts of .NET Core.
 
<b> [Developing Applications with ASP.NET Core](https://www.educative.io/courses/developing-applications-with-asp-net-core) </b>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ny5eyhx1emzmhpm8jmkl.PNG)

 
<a name="what"></a>
 
## What is .NET Core?

.NET Core (often shortened to ".NET") is an open-source, [C#](https://www.educative.io/blog/solid-principles-oop-c-sharp) software framework created by Microsoft in 2016. It is the successor to the .NET Framework and differentiates itself with cross-platform capabilities. While .NET Core does not yet have access to as many libraries as .NET Framework, it is still regularly updated and is projected to continue updates well into the future. These two technologies have recently been merged in November of 2020 into a new framework called .NET 5.
 
`ASP.NET` (Active Server Pages) extends .NET Core with tools to build server-side web applications. It uses the [MVC architecture](https://www.educative.io/blog/mvc-tutorial) to generate its UI and web standard HTML, CSS, and JavaScript to generate behaviors. It includes extensive support for web APIs, cloud-based web applications, and scalability. 

It's also built from the ground up to work with popular tools like [Docker](https://www.educative.io/blog/docker-kubernetes-beginners-guide), Visual Studio, Kestrel, [jQuery](https://www.educative.io/blog/what-is-jquery-javascript-library), and more. .NET is often used with Entity Framework Core, an object-relational mapping framework helpful for working with databases.
 
While often overlooked, `ASP.NET` is a strong stack to know because of its wide popularity in enterprise companies like banks, business-to-business sellers, and investment firms. Some notable users of `ASP.NET` are Slack, Mastercard, and Alibaba.

<br>


### Features of .NET vs. `ASP.NET`


**.NET Core includes:**
 
- Cross-platform support for different computer operating systems, mobile devices, and even game consoles. 
- Support for C#, F#, and Visual Basic programming languages
- Base libraries for working with strings, dates, files/IO, etc.
- Editors and tools for Windows, Linux, macOS, and Docker

**`ASP.NET` adds:**
 
- Support for processing web requests in C# or F#
- Razor page templating syntax for building dynamic web pages using C#
- Libraries for common web patterns like MVC
- An authentication system featuring libraries, a database, and template pages for handling logins with multi-factor authentication and external authentication with third-parties like Google, Twitter, Facebook, etc.
- Editor extensions that implement syntax highlighting, code completion, and other functionality tuned for web development.

<br>
 
<a name="structure"></a>
 
## `ASP.NET` MVC Project Structure

Many developers choose to complete their `ASP.NET` Core projects in MVC structure because of its widespread popularity. 

Let's walk through each of the core components found in an average MVC structured `ASP.NET` Core web app.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nryn6tebm1t2t1lentku.PNG)

<br>
 
### Models

`/Models/` is the "M" in MVC. The `/Models/` folder contains all of your model classes. By default, this folder only has the `ErrorViewModel.cs` file which is a default file that handles exceptions.
 
Model classes allow you to map data to your database. A model class usually consists of attributes along with their “getter” and “setters”. Attributes are essentially the data that any instance of this model class should have values for.
 
The number of model classes and types of attributes in those model classes depends on your application requirements. For example, an app that manages employee data could have a model class `Employee` with attributes `name`, `department`, and `rank` because these attributes apply to all employees.
 
```c#
public class User
{
    public int ID { get; set; } //ID attributes are recognized as keys for the object by Entity
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsActive { get; set; }
}
```
 
<br>
 
### Controllers

`/Controllers/` is the "C" in MVC. The `/Controllers/` folder consists of all of your controller classes. By default, it has the `HomeController.cs` file in it.
Controller classes are where your application logic resides. .NET requires every controller class to implement the `IController` interface as it contains essential support for views.
 
```C#
public class UsersController : Controller
```
 
Controllers are also where you implement dependency injection, which establishes a connection between controllers and your database context. This allows you to `use _context` throughout your controller class to access your database without having to initialize any object.
 
Methods inside a controller are called “action methods” as they return an "action result". The name of an action method is used to map its URL endpoint. For example, if the controller name is UserController and the name of an action method is Details, then there is a URL endpoint `/Users/Details/` that can be accessed and that will trigger the Details action method.
 
This ability to access different pages under the same domain name is called **Routing**. Incoming HTTP requests are matched with the corresponding URL endpoint (often an action method), which then returns your programmed response. Similar to routes in computer filing systems, different parts of the route are differentiated by slashes: `Domain/Model/method`
 
The framework extracts the route from the name of the controller. For example, if a controller’s name is `UsersController`, your route will be `/Users`. 
A URL of the form `Controller1/Method1` maps to a method named `Method1` in the `Controller1 class`. If the name of the Users class method is `SignUp()`, then the route will be `/Users/SignUp/`. 
The default action method triggered when a user accesses the controller URL is `Index()`. This executes the behavior set in the `Index.cshtml` file in the views folder.
 
```c#
// GET: Users
public async Task<IActionResult> Index()
{
    return View(await _context.Users.ToListAsync());
}
```

<br>
 
### Views

`/Views/` is the "V" in MVC. The `/Views/` folder contains all of your files that will be used to display a UI to the user that they can interact with. By default, this folder has two more folders: `/Home/` and `/Shared/`. Both `Index.cshtml` and `_Layout.cshtml` folders are mostly responsible for your output.
 
Views allow users to see your data in a user-friendly format. They are responsible for anything your end-user sees on their screen. Views in `ASP.NET` are written in Hypertext Markup Language (HTML and CSS), along with some additional syntax to represent dynamically changing data.
 
The views generated maps to your controller’s action methods. For example, the `Index()` method has a mapped view called `Index.cshtml` and `Create()` method has a view called `Create.cshtml` and so on.
Files in the Views folder that use methods or data from models must have a model declaration at the start that allows you to access the attributes of the listed model class.

```js
@model IEnumerable<<t>People.Models.User</t>> 
```
In this case, you can read and extract data and attributes from `User` classes.
The simplest view request is an attribute request. This allows you to read the value of an attribute from a paired model class. 
 
```
@Html.DisplayNameFor(model => model.Name)
```
 
Here is an example of an `Index.cshtml` file in Views that displays simple text. As it does not call any methods or use any model data, we do not need to link a model at the start.
 
```c#
ï»¿@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
```


<br>
 
### Properties

The `/Properties/` folder contains a `launchSettings.json` file. This file tells the framework how to launch this application. 

It conveys the information by describing which commands to run, the environment variables to set, and the applications (such as a browser) to launch with the application. .NET Core uses this information to not only run the application but for debugging purposes as well.
 
```json
{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:1779",
      "sslPort": 44366
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "People": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
```

<br>
 
### `/Startup.cs` and `/Program.cs` 

This is where your application starts. .NET Core is a console application configured to run a web application. 

`Program.cs` contains your `main` method and `Startup.cs` contains all your beginning configurations. These configurations are essentially instructions on how you want the application to start and execute.

```c#
// Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace People
{
    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>();
                });
    }
}

```

```c#
// Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace People
{
    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.AddControllersWithViews();
        }
        // 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("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
```

<br>
 
### `appsettings.json `

`appsettings.json` is used to write connection strings or application-specific settings. You can use it to store different configuration settings that include database connection strings, setting up a variable with a global scope, and more. 

`appsettings.Development.json` is similar, but it is only used in a development environment. So, any configurations applied here will not be reflected in the production environment.
 
```json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
```
 
<br>
 
### `.csprof` 

`.csprof` is an XML file. When a new project is created, you receive a file with the same name that you set the project’s name to, and its extension will be `.csprof`. This file represents a C# project file.

Here's an example:
 
```html
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>
</Project>
```


<a name="non-mvc"></a>
 
## Non-MVC Architectures

<br>

### Razor Pages

Razor Pages are the default web development format in `ASP.NET` Core. They're a page-based model built into `ASP.NET` Core MVC. It has similar features to MVC but has its own syntax and a less cluttered layout. 

In MVC style, parts of your application are broken into folders for controller, model, and view. The Razor Pages structure doesn't have separate folders and instead uses a single "Pages" folder as a route folder for all parts. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0sqs273n4meyzywcpta.PNG)

Instead of a separate controller with actions and each action representing a view, Razor Pages are a compact version MVC style that attaches the controller or view model directly to the page.

<br>
 
### Repository

Repositories are a special type of class used to add an abstraction layer between data access and your controllers. It is not used in MVC formatted programs but is important to other types of `ASP.NET` Core apps, such as Razor Pages apps. 
 
This helps promote loose coupling,  isolate your application from changes in the data store, and facilitates unit testing. It also saved you from writing the same queries across multiple controllers that achieve the same purpose.
 
First, you create an interface with all of the declarations of the functions responsible for performing CRUD operations. Then, you create a repository class and inject your database context. These repository classes implement the interface’s functions and provide their logic for handling operations. One of these repositories is then injected into your controller to provide functionality and so you don't need to inject your database directly into your controllers.
 
```c#
public interface IUserRepo
{
    User CreateUser(User user);
    IEnumerable<User> GetAllUsers();
    User GetUserById(int id);
    User UpdateUser(User user);
    User DeleteUser(int id);
}
```
 
> It's best practice to title all C# interfaces with the prefix "I" to indicate their interface status at a glance.

<br>
 
### JSON Web APIs

JSON is an acronym for JavaScript Object Notation. It is a file format that stores data objects in a human-readable form. It is the most popular format when it comes to creating and consuming APIs. Many applications are developed with `ASP.NET` at the back-end and get implemented into a front-end framework like [React](https://www.educative.io/blog/what-is-react-tutorial), Blazor, Bootstrap, or [Angular](https://www.educative.io/blog/angularjs-tutorial) using JSON web APIs. 
Here's an example of a JSON file:
```json
[
    {
        "id":1,
        "name":"James Bond",
        "email":"James@Bond.co.uk",
        "password":"password",
        "phoneNumber":0070000000
    }
]
```
 
The square brackets `[ ]` indicate a list or an array of objects. Curly brackets `{ }` represent a JSON object. Inside this object, there are key-value pairs of different data types, key "name" with value "James Bond".
 
JSONs are manipulated with a set of HTTP methods similar to CRUD. Every HTTP request uses a specific method. The default method is `GET`, but you can use `POST`, `PUT`, or `DELETE` if you want different behaviors. 
 
<br>

**GET**

The `GET` method is used to fetch a resource from the server to the client. In the case of JSON web APIs, the resource can be a JSON object or a list of JSON objects.
 
```json
GET /index.html
```
 
<br>

**POST**

The `POST` method is used to send data from the client to the server. The server then saves the data. In the case of JSON web APIs, this can be a JSON object or a list of JSON objects.
 
```json
POST /test
```
 
<br>

**PUT/PATCH**
 
Both `PUT` and `PATCH` are used to modify data. However, there is a slight difference between the two. In `PUT`, the entire object is replaced with a new object. Whereas in `PATCH`, only the modified part of an object is replaced.
This is similar to the `Update` method in CRUD.
 
```json
PUT /new.html HTTP/1.1
PATCH /file.txt HTTP/1.1
```
 
<br>

**DELETE**
 
The `DELETE` method is used to send a request from the client to the server or to delete a record. The server takes the request and removes the record accordingly.
 
```json
DELETE /file.html HTTP/1.1
```

<br>
 
<a name="hello-world"></a>
 
## Hello World: How to create an `ASP.NET` web app

Now, let's get hands-on and write your first `Hello-World`. For this example, we'll use Razor Pages and .Net Core CLI as these are the default tools. You'll also need .NET Core 3.1 SDK or later for everything to work properly.
 
<br>
 
### Create a project

Open your command shell, and enter the following command:
 

```cmd
dotnet new webapp -o aspnetcoreapp
```
 
This will create a new web app, indicated by the `webapp` parameter.

 The `-o aspnetcoreapp` parameter creates a directory named `aspnetcoreapp` with all the source files for our app.
 
<br>
 
### Trust the development certificate

Now enter:
 
```
dotnet dev-certs https --trust
```
 
This sets your computer to trust the HTTPS development certificate. Without this step, later commands will be blocked.
 
<Br>
 
### Run the app
Next, enter:
 
```
cd aspnetcoreapp
dotnet watch run
```
 
This selects the web app project created in step 1, then tells .NET to run it. 

Once the command shell tells you it has started, copy the following into your browser bar: `https://localhost:5001`.
 
<br>
 
### Edit Razor Page

Open `Pages/Index.cshtml` and modify the `<p>` text to say:
 
```
    <p>Hello, world! The time on the server is @DateTime.Now</p>
```
 
Afterward, your file should look like this:
 
```js
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Hello, world! The time on the server is @DateTime.Now</p>
</div>
```
 
Once you're done, save the file and refresh your browser to the same `localhost` IP. You'll see a nice welcome message!
 
> This step is the same using either the MVC or Razor Page approach.

<br>
 
<a name="next"></a>
 
## Advanced concepts to learn next

Congratulations on completing your first .NET Core application! You're off to a great start in your bright .NET career. 
 
Some next concepts to learn along your journey are:
 
- .NET apps debug techniques
- Database seeding
- Authentication
- Custom [SQL Queries](https://www.educative.io/blog/what-is-database-query-sql-nosql)
- Validation
- Tag Helpers
- Middleware
 
To help get you up to speed quickly, Educative has created the course [**Developing Applications with ASP.NET Core**](https://www.educative.io/courses/developing-applications-with-asp-net-core). This course will walk you through each of these advanced concepts with hands-on code practice. 

By the end, you'll have the .NET skills you need to stand out in future interviews.
 
*Happy learning!*
 
<br>
 
### Continue reading about software architectures
- [Microservices Architecture Tutorial: all you need to get started](https://www.educative.io/blog/microservices-architecture-tutorial-all-you-need-to-get-started)
- [How to Design a Web Application: Software Architecture 101](https://www.educative.io/blog/how-to-design-a-web-application-software-architecture-101)
- [Top 5 technologies for building a Microservices Architecture](https://www.educative.io/blog/top-technologies-microservices-architecture)