ASP.NET Core MVC 2.0 Cookbook

3.6 (7 reviews total)
By Engin Polat , Stephane Belkheraz
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Cross-Platform with .NET Core

About this book

The ASP.NET Core 2.0 Framework has been designed to meet all the needs of today’s web developers. It provides better control, support for test-driven development, and cleaner code. Moreover, it’s lightweight and allows you to run apps on Windows, OSX and Linux, making it the most popular web framework with modern day developers.

This book takes a unique approach to web development, using real-world examples to guide you through problems with ASP.NET Core 2.0 web applications. It covers Visual Studio 2017- and ASP.NET Core 2.0-specifc changes and provides general MVC development recipes. It explores setting up .NET Core, Visual Studio 2017, Node.js modules, and NuGet. Next, it shows you how to work with Inversion of Control data pattern and caching. We explore everyday ASP.NET Core MVC 2.0 patterns and go beyond it into troubleshooting. Finally, we lead you through migrating, hosting, and deploying your code.

By the end of the book, you’ll not only have explored every aspect of ASP.NET Core MVC 2.0, you’ll also have a reference you can keep coming back to whenever you need to get the job done.

Publication date:
February 2018
Publisher
Packt
Pages
668
ISBN
9781785886751

 

Chapter 1. Cross-Platform with .NET Core

This chapter is an introduction to explain all the new concepts and features included in ASP.NET Core 2.0.

Some of the following explanations are mandatory to understand all the options available in ASP.NET Core.

In this chapter, we will cover:

  • Installing or updating .NET Core
  • Managing NuGet packages in ASP.NET applications
  • Creating and running an ASP.NET Core MVC application on Linux
  • Creating and running an ASP.NET Core MVC application on Linux with Docker
  • Creating and running an ASP.NET Core MVC application on macOS
  • Creating and running an ASP.NET Core MVC application on Azure
 

What is ASP.NET Core 2.0?


This new version of ASP.NET is quite a revolution in the Microsoft ecosystem.

Before ASP.NET Core, ASP.NET was not open source, and ran only on Windows. To develop ASP.NET applications, most developers used Visual Studio as IDE. It was not mandatory, because we could use Notepad with CSharp or VB compilers (which were always free), but so much easier with VS even with an express edition. At that time, the only way to run .NET applications on Linux and macOS was to use Mono, an open source cross-platform version of the .NET Framework.

The ASP.NET Core version 2.0 is far more flexible. You can develop on any OS (at least Windows, Linux, and macOS), use various tools such as Visual Studio, Visual Studio Code, or even Sublime Text. ASP.NET Core is now modular, more maintenable, and has increased performance. By design, it is cloud-ready and middleware-based.

With the new version of ASP.NET, IIS is not the only possible host. You can host your ASP.NET applications on other web servers, such as Kestrel on macOS and Linux.

Among all the changes, some of the most important were the fusion of MVC and Web API, and the deletion of WebForms, Service locator, and System.Web.

All the duplicate libraries existing both in MVC and Web API, such as Controllers, Actions, Filters, Model Binding, and Dependency Resolver, are now the same unified classes.

The strong dependency on the heaviest library used in ASP.NET, System.Web, is now deleted to make ASP.NET Core MVC more modular, middleware-compliant, and platform-independent.

Note

All the source code for ASP.NET Core MVC is available in its GitHub repository at https://github.com/aspnet/mvc. We can find all the ASP.NET Core repositories at https://github.com/aspnet, and all the .NET Core repositories at https://github.com/microsoft/dotnet.

 

What's new in ASP.NET and CLR?


We now will use two frameworks, and have two options to develop web applications:

  • The Framework 4.6, which offers us maximum compatibility with legacy apps and the previous .NET frameworks. Framework 4.6 only works on Windows. One of the most interesting new features of ASP.NET 4.6 is HTTP2, which gives us:
    • Asynchronous ModelBinding
    • Ability to always encrypt exchanges on the web
    • Pre-population of the browser's cache
    • Interruption of a TCP connection without closing
  • The .NET Core 2.0, which is the modular and lightweight approach above the Core CLR to develop cross-platform applications.

We can use them independently, or both at the same time, in order to create a two-frameworks-compatible application, and the old DLLs of the legacy applications will have to migrate on .NET Core version 2.0.

Two versions of the .NET framework can also live side by side in the same application; for example, .NET Framework 4.6 and .NET Core 2.0.

Note

Before .NET Core, Mono was used as and open source cross-platform .NET Framework. All the libraries outside the framework are optional, available in the form of packages.

Before .NET Core, a .NET application could only be executed under Windows, because only Windows could instantiate the CLR. If IIS was in charge of the instantiation, WebEngine.dll was responsible for instantiating CLR.

Now, we have a new SDK with a lot of tools to allow us to execute ASP.NET applications outside IIS and independently from any web server.

 

Installing or updating .NET Core


In this recipe, we will learn how to set up .NET Core. This recipe is pivotal if you are installing it for the first time.

Installing .NET Core is a relatively easy task. Microsoft did a great job to make it easy to install .NET Core to any computer. All we need is a clean computer and an internet connection.

How to do it...

The first step is to open a web browser and navigate to the http://dot.net/core site. It'll detect a host operating system, and will show downloading and installation steps.

  • Installation for Windows: On the Windows platform, we can easily download .NET Core SDK installer by clicking the Download .NET Core SDK button and beginning setup. Once setup finishes, you're ready to develop/run .NET Core applications on the machine.
  • Installation for Linux: On the Linux platform, there are different commands to install .NET Core on Ubuntu, RedHat, Debian, Fedora, CentOS, and Suse distribution. We should select the correct distribution on the page, and execute some Terminal commands by following preceding instructions.
  • Installation for macOS: On the macOS platform, it's as easy as downloading the .NET Core SDK package.
  • Installation for Docker: There is another platform available to deploy and run .NET Core applications: Docker. Docker is simply a virtualization platform. You may run Docker on the machine and deploy your .NET Core applications into Docker. Once you successfully deploy an application to Docker, it's easy to run more than one instance of it.

Docker usually helps developers to scale their applications with minimum management cost.

How it works...

After installing .NET Core 2.0 SDK, you can open the Terminal/Command Prompt window and run the following command:

dotnet --info

This command displays the installed and most recent .NET Core SDK version (2.0.2 at the time this book was written), Runtime Environment info (OS platform, architecture, version, and more), and .NET Core SDK installation path:

We can see Base Path includes the .NET Core SDK version. If we remove that version from the path and open that path in Finder/Explorer, we can see all the installed .NET Core SDK versions:

It's as easy as deleting a folder to remove any .NET Core SDK version on a machine.

 

Managing NuGet packages in ASP.NET Core applications


Now in ASP.NET Core, every dependency and every DLL is a NuGet package that can be managed with dotnet CLI.

How to do it...

With dotnet CLI, you will be able to:

  • Install and uninstall packages
  • Build an application
  • Creating assemblies for an application
  • Restore packages by downloading the entire graph of dependencies for the dependency asked
  • Publish an application with all the necessary files to execute the application event if there is no .Net Core installed on the machine
 

Creating an ASP.NET Core MVC application on Linux


In this recipe, we will create an ASP.NET Core MVC application on Linux. In order to perform this feature, we will have to install all the necessary libraries, components, and IDE on Ubuntu.

Getting ready

For cost consideration, we may be interested in hosting our websites on a Linux infrastructure. With cloud possibilities, we can consider hosting a Linux VM with ASP.NET Core capabilities.

For this recipe, we will use Ubuntu 17.10, but you can use a different Linux distribution such as Debian, CentOS, Fedora or any Linux distribution that supports a Docker Engine.

Before .NET Core, there was the Mono Framework (http://www.mono-project.com/) to run a .NET application on Linux. Mono is an open source and a cross-platform port of the .NET Framework, which contains an Apache module to host ASP.NET applications.

For now, .NET applications always need Mono to run on Linux or OS X, because not all the BCL (The .NET Framework base class library) is fully ported on Linux.

To host our ASP.NET Core 2.0 application on Linux, we will use Kestrel (you can read more about this at https://github.com/aspnet/KestrelHttpServer) as a WebServer, which is a lightweight cross-platform web server able to execute ASP.NET Core code. Kestrel uses Libuv internally as a multi-platform asynchronous IO and TCP library, also used by Node.js.

For the moment, there's no other web server we could use to host ASP.NET Core applications on Linux or macOS, and Kestrel is not production-ready. We can also use IIS or WebListener as a web server to host ASP.NET Core applications, but exclusively on Windows.

How to do it...

After installing .NET Core on Linux, creating a new project is easy.

Let's start creating a new project:

  1. Run dotnet new mvc from the command line. This command will create a new ASP.NET Core MVC project with the same name as the containing folder. If we want to give a different name to the project, -n PROJECTNAME switch should be added
  1. Next, we need to run dotnet restore in the project folder. Most IDEs run dotnet restore in the background for us, such as Visual Studio and Visual Studio Code

How it works...

The dotnet CLI will generate all the necessary files you need for the project template we select.

The dotnet run command will be used to launch the ASP.NET Core MVC project:

 

Creating an ASP.NET Core MVC application on Linux with Docker


In this recipe, we will learn how to create an ASP.NET Core MVC application on Linux with Docker, the new Container technology.

Getting ready

We also have the option to use Docker to create, host, and publish an ASP.NET Core MVC application on Linux. Docker is a piece of operating system and software you will use to run your applications as a server (generally used as a VM locally, or in the cloud). We use Docker Containers as a lightweight VM with only the necessary files (system, tools, runtime, libraries, and code) for running applications, which starts much more quickly and runs independently from the environment it evaluates.

How to do it...

In our recipe, we will locally create a Docker Container with a Linux Ubuntu 17.10 VM to publish and host our ASP.NET Core MVC application.

In this recipe, we will do the following:

  1. Before beginning, you can install Nautilus, a file manager for a gnome-like explorer on Windows, which allows you to open the Terminal by right-clicking in a folder:
$ apt-get install nautilus-open-terminal 

$ killall nautilus && nautilus
  1. Download and install Docker on our Ubuntu VM:
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9 

$ sudo sh -c "echo deb https://get.docker.com/ubuntu docker main > /etc/apt/sources.list.d/docker.list" 

$ sudo apt-get update 

$ sudo apt-get install lxc-docker 
  1. Add the current user to Docker group, then log out and log in again:
$ sudo usermod -aG docker  

$ sudo service docker restart

Note

Note: We don't need to write sudo before the command lines anymore, because now we have enough rights to execute the command without writing sudo.

  1. Download project.json and Starup.cs from the HelloWeb sample, at https://github.com/aspnet/Home/tree/dev/samples/latest/HelloWeb. These two files are the only mandatory files required to run our application.
  2. Create a directory named HelloWeb, and place the two previous files inside.
  1. Create a file without an extension inside called Dockerfile, and insert in the following code:
# This code will download and use the last ASP.NET 5 Docker 
 # image based on Mono at 
 # https://github.com/aspnet/aspnet-docker/blob/master/1.0.0-
 # rc1-update1/Dockerfile

FROM Microsoft/aspnet:latest 

# This code copies the project into the folder and restores 
 # the packages using dotnet CLICOPY . /app
 WORKDIR /app
 RUN ["dotnet","restore"] 

# Open this port in the container 
EXPOSE 5000 

# Start application using DNX and the command from 
 # project.json to call kestrel 
ENTRYPOINT ["dotnet","run"] 
  1. Save and close Dockerfile.
  2. Then, verify the existing containers (not mandatory):
$ sudo docker images
  1. We can also check the running containers (not mandatory):
$ docker ps
  1. You can build your application now:
$ docker build -t 
  1. Run it (port 5004 is the default port for Kestrel):
$ docker run -t -d -p 5004:5004 
  1. You can see the home page at http:localhost:5004.

How it works...

A web server usually uses port 80 for web applications, while Kestrel will use port 5000 or 5004. We know that we cannot open ports lower than 1024 with default user permissions on Linux. To host ASP.NET Core applications using port 80, and to be production-ready on Linux, we will have to use Nginx with Kestrel to bring us all the web server features we need that Kestrel doesn't have, like load balancing, caching, and security, among others.

We can think of Docker Container as a mini VM with the minimum OS and software components you need to run the applications, isolated from the other application containers. Docker is lightweight, open, and secure, isolating applications from each other. You can consult the Docker documentation at https://www.docker.com/.

We can create a Docker Container on Windows, macOS, Linux (Ubuntu, RedHat, Suse, Arch, Debian, and so on), and on the cloud (Azure, AWS, Google, and so on). It will generally run on Linux distributions, but Windows will also support it.

 

Creating an ASP.NET Core MVC application on macOS


In this recipe, we will learn how to install the .NET Core components in order to create an ASP.NET Core MVC application on macOS.

Getting ready

Because macOS is based on Unix, it is possible to run a .NET application on it with the Mono project. As mentioned in the previous recipe, for the moment, .NET application needs Mono to run on Linux or macOS.

To install Mono, we use Homebrew (http://brew.sh/), which is a package manager for macOS.

Note

We suppose that you have the necessary privileges to execute all these commands. If not, prefix sudo before all the command lines and you should be good to go.

How to do it...

In this recipe, we will do the following:

  1. Install Homebrew by entering this command at a Terminal:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 
  1. Use Homebrew to get DNVM, DNX, and DNUusing the commands as follows:
$ brew tap aspnet/dnx 

$ brew update 

$ brew install dnvm 

$ source dnvm.sh
  1. Install Node.js and npm (the npm will be installed automatically with Node.js):
$ brew install node
  1. Verify Node.js and NPM versions:
$ node -v 

$ npm -v

The version currently being used will be displayed on your screen as follows:

  1. Install Yeoman with Gulp to help automate tasks:
$ npm install -g yo gulp 

$ npm install -g generator-aspnet
  1. Yeoman asks us what type of application we want to create. In our case, we choose Web Application Basic.
  2. After that, Yeoman asks us the name for the application to create, as shown in the following screenshot.
  3. Yeoman will generate all the necessary files to run an ASP.NET Core MVC application. After the project is created, Yeoman shows us the different commands we can use to run the application.
  4. With the command cd "nameoftheapplication", we are placed in the application directory.
  1. After that, we can run the dotnet restore command, which will restore all the dependencies needed to run the application. In the background, this command will connect to the NuGet online repository to download, as NuGet packages the missing dependencies:
  1. Build and run webapp1 typing the following command:
$ dotnet run

After executing the preceding command you get the following output at localhost:5000:

 

Creating and running an ASP.NET Core MVC application on Azure


In this recipe, we will create a web application and deploy it to Azure.

Getting started

We will use Visual Studio 2017 Community Edition, and create a web application using the ASP.NET Core templates in Visual Studio.

How to do it...

  1. First, let's create a new project by clicking New | Project | ASP.NET Core Web Application | Web application to create a web application running with ASP.NET Core:

Note

When you run a web application in Visual Studio 2017, you have the choice to develop, debug, and deploy a web application in two different runtime versions, which have themselves two versions for the processor architecture as follows:

  • CLR x86 (.NET 4.6 in 32 bits, only for Windows)
  • CLR x64 (.NET 4.6 in 64 bits, only for Windows)
  • CoreCLR x86 (.NET Core in 32 bits, cross-platform)
  • CoreCLR x64 (.NET Core in 64 bits, cross-platform)
  1. Let's do our first deployment by creating a website on Azure. To do that, right-click on the root of the project and select Publish....
  2. The Publish Web dialog box will open:
  1. Click Microsoft Azure App Service. The Create App Service dialog box will open:
  1. We have to give an App Name.
  2. Select the Subscription.
  3. Select an App Service Plan, or create one.
  4. Select a Resource Group (optional).
  5. Select a Region (optional).
  6. Select or create a Database Server (optional).
  1. Now the Create button is enabled, we click on it:

In the preceding screenshot, we can see a preview of the deployed files.

  1. Click Publish:

In the preceding screenshot, we can see the result of the build and the publishing in the output window.

In the following screenshot, we can see how our web application deployed on Azure:

Take a look at the screenshot below. We can see the publish settings for the web application in the PublishProfiles folder as one .pubxml file.

How it works...

We can publish the following applications to the Azure platform:

  • .NET web application
  • .NET Core web application
  • Java web application
  • Node.js web application
  • PHP web application
  • Python web application
  • Ruby web application

Azure makes it very easy to deploy and run web-based applications.

About the Authors

  • Engin Polat

    Engin Polat has been involved in many large-scale and medium-scale projects on .NET technologies as a developer, architect, and consultant, and has won many awards since 1999.

    Since 2008, he has been conducting training for many large enterprises in Turkey on Windows development, web development, distributed application development, software architecture, mobile development, cloud development, and so on.

    Browse publications by this author
  • Stephane Belkheraz

    Stephane Belkheraz is a professional software developer with over 16 years' web development experience. He spends his time developing, testing, and architecting exclusive ASP.NET applications with Web Forms, MVC, SQL Server, native JavaScript, AngularJS, and all open source frameworks around the ASP.NET ecosystem.

    Stephane also develops, integrates, and creates multimedia applications with numerous technologies, including Flash, ActionScript, Java, PHP, JavaScript, and CSS.

    Browse publications by this author

Latest Reviews

(7 reviews total)
This is easy and perfect shopping experience! Some books are very good and professional
Otimo livro recomendadoo.
eligible copy - electronic copy

Recommended For You

Book Title
Access this book, plus 7,500 other titles for FREE
Access now