Book Image

ASP.NET Core 2 Fundamentals

By : Onur Gumus, Mugilan T. S. Ragupathi
Book Image

ASP.NET Core 2 Fundamentals

By: Onur Gumus, Mugilan T. S. Ragupathi

Overview of this book

The book sets the stage with an introduction to web applications and helps you build an understanding of the tried-and-true MVC architecture. You learn all about views, from what is the Razor view engine to tagging helpers. You gain insight into what models are, how to bind them, and how to migrate database using the correct model. As you get comfortable with the world of ASP.NET, you learn about validation and routing. You also learn the advanced concepts, such as designing Rest Buy (a RESTful shopping cart application), creating entities for it, and creating EF context and migrations. By the time you are done reading the book, you will be able to optimally use ASP.NET to develop, unit test, and deploy applications like a pro.
Table of Contents (14 chapters)

Introduction to ASP.NET


ASP.NET is a server-side web application development framework, developed by Microsoft, allowing developers to build web applications, websites, and web services.

It is currently fully open source in this URL and is still maintained by Microsoft: https://github.com/aspnet

Basically, ASP.NET has three main programming models: ASP.NET Web Forms, ASP.NET MVC, and ASP.NET Web Pages. They form part of the ASP.NET Framework in this manner:

  • ASP.NET for .NET Framework: This has the following sub sections:
    • Web Forms: This is known for rapid application development. This tries to mimic desktop behavior.
    • MVC: This applies the Model-View-Controller pattern.
    • Web API: This is an MVC-style web service.
    • Single-Page Application: Here, the server gives the initial HTML request, but further rendering happens entirely within the browser.
  • ASP.NET Core: It is the new ASP.NET Platform that runs in a cross-platform manner. Subsections are:
    • Web API: This is primarily used for developing web services.
    • Web Application: This is used for MVC Applications. It can be used for developing web services too. Web API and MVC have become an almost unified thing.
    • Web Application (Razor Pages): Razor Pages is a feature of ASP.NET Core MVC that makes coding page-focused scenarios easier and more productive.

Note

A recent trend for developers is the use of Single-Page Application frameworks on top of web services like Web APIs. However, MVC and Single-Page Application frameworks also play nicely together. In the future, we expect Microsoft to put more effort on .NET Core instead of .NET Framework. .NET Framework is already mature. Perhaps it will be put into maintenance mode but nothing is certain yet.

Even though the end result of all of the preceding programming models is to produce dynamic web pages effectively, the methodologies that they follow differ from each other. Let us discuss ASP.NET MVC.

ASP.NET MVC

ASP.NET MVC is the implementation of the MVC pattern in ASP.NET. The disadvantages of ASP.NET Web Forms which tried to mimic Windows development in the web environment, such as limited control over the generation of HTML, coupling with business code and UI code, hard-to-grasp, and complex page life cycle, are resolved in ASP.NET MVC. As most of the modern applications are controlled by client-side JavaScript libraries/frameworks, such as jQuery, KnockoutJS, AngularJS, and ReactJS, having complete control over the generated HTML is of paramount importance. As for Knockout, Angular, and React, these single-page libraries actually generate the HTML directly within the browser via their own template engines. In other words, the rendering is done in the browser rather than the server. This frees up server resources and it allows the web application to behave just like a disconnected application, as in mobile apps.

Let us talk a bit about the Model-View-Controller pattern and how it benefits the web application development.

The Model-View-Controller Pattern

This is a software architectural pattern which helps in defining the responsibility for each of the components and how they fit together in achieving the overall goal. This pattern is primarily used in building user interfaces and is applicable in many areas, including developing desktop applications and web applications. But I am going to explain the MVC pattern from the context of web development.

Primarily, the MVC pattern has three components:

  • Model: This component represents your domain data. Note that this is not your database. This model component can talk to your database, but the model only represents your domain data. For example, if you are building an e-commerce web application, the model component may contain classes such as Product, Supplier, and Inventory.
  • View: This component is responsible for what to present to the user. Usually, this component would contain your HTML and CSS files. This may also include the layout information governing how your web application looks to the end user.
  • Controller: As the name implies, the controller is responsible for interacting with different components. It receives the request (through the routing module), talks to the model, and sends the appropriate view to the user.

The following image speaks of the MVC pattern:

This separation of responsibilities brings great flexibility to the web application development, allowing each area to be managed separately and independently.

The Code for ASP.NET Core is as follows:

public class ValuesController : Controller
{
 // GET api/<controller>
 public IEnumerable<string> Get()
 {
 return new string[] { "value1", "value2" };
 }
}

Basically, each controller is represented by a class derived from the Controller class, although we can also write controllers without deriving from Controller. Each public method of the controller represents actions.

In this case, if we define a GET method (accessed via www.yoursite.com/controller without writing GET), it returns a string array as a response. How these strings are returned depends on the content negotiation.

A File-Based Project

Whenever you add a file or folder in your file system (inside the ASP.NET Core project folder), the changes will automatically be reflected in your application.

We bundle our static files into one file because for each static file, a browser will make a separate request to the server to retrieve it. If you have 100 CSS and JavaScript files, this means there will be 100 separate requests to retrieve those files. Obviously, reducing the number of requests will certainly improve the performance of your application. Thus, bundling is effectively decreasing the number of requests.

Note

HTTP/2 uses only 1 persistent connection for all files and requests. Thus, bundling is less useful in HTTP/2. However, it's still recommended since HTTP/1.x is here to stay for a long time. The development and deployment of an ASP.NET Core application on a Linux machine will be explained in a later chapter.

These are the important folders and files in a file-based project:

Folder/File

Description

Controllers

This folder contains all of your controller files. Controllers are responsible for handling requests, communicating models, and generating the views.

Models

All of your classes representing domain data will be present in this folder.

Views

These are files that contain your frontend components and are presented to the end users of the application. This folder contains all of your RazorView files.

wwwroot

This folder acts as a root folder and it is the ideal container to place all of your static files, such as CSS and JavaScript files. All the files which are placed in the wwwroot folder can be directly accessed from the path, without going through the controller.

Other files

The appsettings.json file is the configuration file where you can configure application-level settings. Previously, .xml files were used for configuration; however, the .jsonformat is less verbose, and Bower and npm (Node Package Manager) are client-side technologies, supported by ASP.NET Core applications. The Bundle.config file allows us to configure how to bundle our CSS and JS files into one file.

Here's the project structure of ASP.NET Core:

Note

Despite the fact that current ASP.NET Core templates are using Bower, Bower itself is obsolete now. Instead, npm or yarn is recommended. Just like NuGet, the JavaScript world needed package managers as there are hundreds of thousands of libraries and they have complex dependencies on each other. These package managers allow you to automate the installation and upgrades of these libraries by writing single commands from the command line.

Creating Your First Project

Follow this steps to create your first project:

  1. Open up Visual Studio 2017. Navigate to File | New Project | Web. You'll be presented with this screen:
  1. Select ASP.NET Core Web Application. Optionally, give a name to your project, or accept the default. Then, click on OK.
  2. Make sure you select .NET Core 2.0. If it doesn't show up, download .NET Core SDK from https://www.microsoft.com/net/download/ core and restart Visual Studio. Then select Web Application and click on OK.
  3. Right-click on your project and click on Build. This will restore the dependencies.

Creating Your First Application

It is now time to create your first ASP.NET Core application.

Fire up Visual Studio and follow these steps:

  1. Create a project by selecting File | New Project in Visual Studio. The first option is for creating an earlier version of the ASP.NET web application. The second option is for creating the ASP.NET Core application using the .NET Core framework. NET Core supports only the core functionalities. The advantage of using the .NET core library is that it can be deployed on any platform. Select ASP.NET Core Web Application:

Note

Routing and controllers work together to render the correct view. We'll use the name Lesson2 here to avoid reinventing the wheel in Chapter 2, Controllers.

  1. Select the Empty template from the list of ASP.NET Core templates. The second option is for creating the Web API application (for building the HTTP-based services) and the third option is for creating a web application containing some basic functionalities which you can run out of the box, without you ever needing to write anything:

  1. Once you click on OK in the window, as shown in the preceding screenshot (after selecting the Empty template option), a solution will be created, as shown in the following screenshot:
  1. When you run the application (by pressing F5) without any changes, you'll get the simple Hello World! text on your screen, as shown in the following screenshot:

We have not done any coding in this newly created application. So, have you thought about how it displays the text Hello World!?

The answer lies in the Startup.cs file, which contains a class by the name of Startup.

Note

When an exception occurs, we want to display the callstack for better diagnosis, for instance. However, doing so in a production environment would be a security risk. Hence, we have development-specific code.

ASP.NET Core runtime calls the ConfigureServices and Configure methods through the main method. For example, if you want to configure any service, you can add it here. Any custom configuration for your application can be added to this Configure method:

public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment
env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }
  app.Run(async (context) =>
  {
    await context.Response.WriteAsync("Hello World!");
  });
}

There are only a couple of statements in the Configure method. Let us leave aside async, await, and context for the moment in the second statement, which we will discuss later. In essence, the second statement tells the runtime to return Hello World! for all the incoming requests, irrespective of the incoming URL.

When you type the URL http://localhost:50140/Hello in your browser, it will still return the same Hello World!

This is the reason we got the Hello World! when we ran the application.

As we have chosen the Empty template while creating the ASP.NET Core application, no component will have been installed. Even MVC won't be installed by default when you select the Empty template as we did.