40,79 €
Learn to implement ASP.NET Core features to build effective software that can be scaled and maintained easily
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.
This book is written for the ASP.NET developer who wants to deliver professional-standard software, quickly and efficiently. It's filled with hands-on recipes, practical advice, and guidance to help developers with every aspect of the ASP.NET development cycle. Whether you've just started out or are a seasoned pro, the Asp.Net Core 2.0 Cookbook is written for you.
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. 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.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 375
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Edward GordonAcquisition Editor: Chaitanya NairContent Development Editor: Zeeyan PinheiroTechnical Editor: Ketan KambleCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Rekha NairGraphics: Jason MonterioProduction Coordinator: Arvindkumar Gupta
First published: February 2018
Production reference: 1230218
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78588-675-1
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
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.
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.
GauravAroraa has completed an MPhil in computer science. He is a Microsoft MVP, lifetime member of the Computer Society of India (CSI), advisory member of IndiaMentor, certified as a Scrum trainer/coach, XEN for ITIL-F, and APMG for PRINC-F and PRINC-P.
Gaurav is an open source developer and a contributor to TechNet Wiki. In over 20 years of working in the industry, he has mentored thousands of students and industry professionals. You can find him using his twitter handle @g_arora.
Gaurav is the founder of Ovatic Systems LTD, Innatus Curo Software LLC, and Shubh Computing LLP. He has also worked on other Packt books, such as Building Microservices in ASP.NET Core, Learn C# in 7-days, and Building Microservices with .NET Core 2.0 Second Edition.
Jason De Oliveira works as CTO for MEGA International, a software company in Paris. He is an experienced manager and senior solutions architect skilled in software architecture and enterprise architecture.
He loves sharing his knowledge and experiences through his blog and articles and by speaking at conferences. He even conducts software courses as an MCT and coaches his co-workers.
Jason is a Microsoft Most Valuable Professional (MVP C#), and has worked on numerous books on.NET, such as Learning ASP.NET Core 2.0 and .NET 4.5 Expert Programming Cookbook.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
ASP.NET Core MVC 2.0 Cookbook
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the authors
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Get in touch
Reviews
Cross-Platform with .NET Core
What is ASP.NET Core 2.0?
What's new in ASP.NET and CLR?
Installing or updating .NET Core
How to do it...
How it works...
Managing NuGet packages in ASP.NET Core applications
How to do it...
Creating an ASP.NET Core MVC application on Linux
Getting ready
How to do it...
How it works...
Creating an ASP.NET Core MVC application on Linux with Docker
Getting ready
How to do it...
How it works...
Creating an ASP.NET Core MVC application on macOS
Getting ready
How to do it...
Creating and running an ASP.NET Core MVC application on Azure
Getting started
How to do it...
How it works...
Visual Studio 2017, C# 6, IDEs, and Roslyn
Introduction
Working with Visual Studio 2017
How to do it...
Working with Visual Studio Code
Getting ready
How to do it...
How it works...
Installing and using OmniSharp on macOS
How to do it...
How it works...
See also
Installing and using OmniSharp on Linux
Getting ready
How to do it...
Working with Roslyn
Getting ready
How to do it...
How it works...
APIs
Using C# 6 new features
How to do it...
See also...
Working with npm, Frontend Package Managers, and Task Runners
Introduction
Using and creating npm modules
Getting ready
How to do it...
Creating a node package
Publishing the package
How it works...
There's more...
Managing frontend dependencies with Bower
Getting ready
How to do it...
How it works...
There's more...
See also
Compiling LESS files to CSS files with Grunt
Getting ready
How to do it...
How it works...
There's more...
See also
Bundling and minifying JavaScript files with Gulp
Getting ready
How to do it...
How it works...
There's more...
Using Yeoman code-generated templates
Getting ready
How to do it...
How it works...
Using JSPM
Getting ready
How to do it...
How it works...
Reusing Code with NuGet
Introduction
Managing NuGet packages
Getting ready
How to do it...
See also
Creating a NuGet package with the NuGet package class library
Getting ready
How to do it...
The old way
The new way
Creating a local NuGet repository and consuming packages from it
How to do it...
Creating a NuGet package with NuGet Package Explorer
How to do it...
Sharing NuGet packages with the community
How to do it...
Creating an Azure NuGet repository
How to do it...
SOLID Principles, Inversion of Control, and Dependency Injection
Introduction
SOLID principles
Inversion of control
Dependency injection (DI)
DI containers
Configuring a DI container
IOC versus service locator
Life cycles
Implementing DI with Native IOC in ASP.NET Core
Getting ready
How to do it...
How it works...
There's more...
Using the life cycles available in ASP.NET Core
Getting ready
How to do it...
How it works...
Implementing DI with Autofac
Getting ready
How to do it...
How it works...
Implementing DI with StructureMap
How to do it...
How it works...
Implementing DI with DryIoc
Getting ready
How to do it...
How it works...
Data Access - EF7 with Repository, SQL Server, and Stored Procedures
Introduction
DbContext
Entity Framework (EF) approach
Configuring the IOC life cycle for the repository pattern
Getting ready
How to do it...
Using EF with an existing database
Getting ready
How to do it...
Using an InMemory provider
Getting ready
How to do it...
How it works...
Managing a long request batch
Getting ready
How to do it...
There's more...
Using a stored procedure with EF
Getting ready
How to do it...
Writing an EF provider
Getting ready
How to do it...
See also
Accessing data with Micro ORMs, NoSQL, and Azure
Introduction
Micro ORMs
NoSQL
Accessing data with Dapper
Getting ready
How to do it...
There's more...
Accessing data with OrmLite
Getting ready
How to do it...
Accessing data with MongoDb
Getting ready
How to do it...
How it works...
There's more...
Accessing data with Windows Azure storage tables
Getting ready
How to do it...
How it works...
Accessing data with Azure storage Blobs
Getting ready
How to do it...
Accessing data with SQL Azure
Getting ready
How to do it...
Cache and Session - Distributed, Server, and Client
Introduction
Using .NET Cache with MemoryCache
Getting ready
How to do it...
Caching HTML with Cache TagHelpers
Getting ready
How to do it...
How it works...
Using ResponseCache attribute
Getting ready
How to do it...
How it works...
Using Session
Getting ready
How to do it......
How it works...
Using Redis as Cache on-Premises
Getting ready
How to do it...
How it works...
Using Redis as a cache on Azure
Getting ready
How to do it...
Caching with HTML5 cache manifest
Getting ready
How to do it...
How it works......
Caching with HTML5 localStorage and sessionStorage
Getting ready
How to do it...
How it works......
See also
Routing
Before ASP.NET Core
Since ASP.NET Core
MVC and Web API routing
The route order
Routing with ASP.NET Core
Creating a route using convention routing
How to do it...
How it works...
Creating a route using attribute routing
Getting ready
How to do it...
Creating a custom route using IRouter
Getting ready
How to do it...
Creating a route constraint
Getting ready
How to do it...
How it works...
Creating a domain route
Getting ready
How to do it...
Creating SEO-friendly routes
Getting ready
How to do it...
ASP.NET Core MVC
Injecting dependencies and configuring IoC for a controller
Getting ready
How to do it...
Using ActionResults
Getting ready
How to do it...
Creating and working with areas
Getting ready
How to do it...
Creating and using POCO controllers
Getting ready
How to do it...
Creating and using controllers with MediatR
Getting ready
How to do it...
How it works...
Managing exceptions
Getting ready
How to do it...
Web API
Using ActionResult
Getting ready
How to do it...
How it works...
Configuring content negotiation
Getting ready
How to do it...
Configuring cross-domain origin requests
Getting ready
How to do it...
Using Swagger
Getting ready
How to do it...
How it works...
Testing Web API
Getting ready
How to do it...
There's more...
Managing exceptions
Getting ready
How to do it...
There's more...
Filters
Introduction
Managing authentication and authorization with policies, requirements, and filters
Getting ready
How to do it...
Authentication
There's more...
Managing dependency injection with filters
Getting ready
How to do it...
How it works...
Creating and using an action filter
Getting ready
How to do it...
Creating and using a result filter
Getting ready
How to do it...
Creating and using a resource filter
Getting ready
How to do it...
Creating and using an exception filter
Getting ready
How to do it...
Using a filter globally versus using a middleware
Getting ready
How to do it...
There's more...
Views, Models, and ViewModels
Creating and using a ViewModel with AutoMapper
Getting ready
How to do it...
Understanding and using ModelBinding
Getting ready
How to do it...
How it works...
Creating our own model binder
Getting ready
How to do it...
Understanding and using a value provider
Getting ready
How to do it...
Configuring and using validation
Getting ready
How to do it...
Razor and Views
Managing namespaces in views with ViewImports
Getting ready
How to do it...
Creating a strongly typed Partial view
Getting ready
How to do it...
Configuring view and area locations
Getting ready
How to do it...
How it works...
Using dependency injection in views
Getting ready
How to do it...
Creating HTMLHelpers
Getting ready
How to do it...
How it works...
TagHelpers and ViewComponents
Using Environment, Script, and Link TagHelpers
Getting ready
How to do it...
Using Form TagHelpers
Getting ready
How to do it...
Creating TagHelpers programmatically
Getting ready
How to do it...
There's more...
Creating a reusable view component
Getting ready
How to do it...
How it works...
Creating a view component/controller class
Getting ready
How to do it...
How it works...
OWIN and Middleware
Understanding OWIN, Katana, and the new ASP.NET Core HTTP pipeline
OWIN - an abstraction for decoupling
Katana - the Microsoft OWIN implementation
A new OWIN implementation with ASP.NET Core
The ASP.NET Core pipeline
Middleware
HTTP modules and HTTP handlers
Using inline middleware code as anonymous methods - Use, Run, Map, and MapWhen
Getting ready
How to do it...
Creating a reusable middleware component
Getting ready
How to do it...
Migrating an HTTP handler to middleware
Getting ready
How to do it...
Migrating HTTP modules to middleware
Getting ready
How to do it...
Security
Introduction
Authentication in the real world
Authentication sample
Authentication in ASP.NET, using cookie authentication
Getting ready
How to do it...
How it works...
Authentication using authorization servers
Getting ready
How to do it...
Using Facebook as an authorization server
Using Google as an authorization server
How it works...
Managing identity
Getting ready
How to do it...
How it works...
Securing data with Hashing
Getting ready
How to do it...
How it works...
Securing data with Encryption
Getting ready
How to do it...
How it works...
Frontend Development
Using Bootstrap
Getting ready
Advantages of using CDN
How to do it...
How it works...
Writing clean JavaScript
Getting ready
How to do it...
How it works...
RequireJS
Getting ready
How to do it...
How it works...
Typescript
Getting ready
How to do it...
How it works...
Writing and executing unit tests in JavaScript
Getting ready
How to do it...
How it works...
Debugging JavaScript code in browsers
Getting ready
How to do it...
How it works...
Deployment and Hosting
Deployment options
Getting ready
How to do it...
How it works...
Hosting an ASP.NET Core web app on IIS
Getting ready
How to do it...
How it works...
Hosting an ASP.NET Core web application on Kestrel
Getting ready
How to do it...
How it works...
Hosting an ASP.NET Core web app on Azure
Getting ready
How to do it...
Deploying an ASP.NET Core web app to Azure with Visual Studio Code
Deploying an ASP.NET Core web app to Azure with Visual Studio Community Edition
How it works...
Hosting an ASP.NET Core web app in Docker containers
Getting ready
How to do it...
How it works...
Other Books You May Enjoy
Leave a review - let other readers know what you think
The ASP.Net Core 2.0 Framework is designed to meet 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 follows a unique approach to web development, using real-world examples that guide you through problems with ASP.NET Core 2.0 web applications. It covers VS2017 and ASP.NET Core 2.0-specific 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 ASP.NET Core MVC 2.0 , into troubleshooting. Finally, we will lead you through migrating, hosting, and deploying your code.
By the end of this book, you'll not only have explored every aspect of ASP.NET Core 2.0, you'll also have a reference you can keep coming back to whenever you need to get the job done.
This book is for developers who want to learn to build web applications and make a career building web applications using ASP.NET Core.
If you're new to programming, this book will introduce you to the patterns and concepts used to build modern web applications.
This book is also for those who are working on other web frameworks and want to learn more about ASP.NET Core.
You'll learn how to build a web app from scratch; this book will give you a starting point so you can learn more advanced topics.
Chapter 1, Cross-Platform with .NET Core, dives deep into what .NET Core is, what its core components are, and creating ASP.NET Core web projects using the .NET Core CLI.
Chapter 2, Visual Studio 2017, C# 6, IDEs, and Roslyn, covers the use of Visual Studio 2017, Visual Studio Code, and Atom as C# editors. Also, we'll investigate the new features that come with C# 6 and use Roslyn compiler as a service.
Chapter 3, Working with NPM, Frontend Package Managers, and Task Runners, covers using and creating npm modules and using Bower, Grunt, Gulp, and Yeoman.
Chapter 4, Reusing Code with NuGet, guides you though manage NuGet packages, creating new NuGet packages, using previously created packages, and creating a new NuGet repository to privately list NuGet packages.
Chapter 5, SOLID Principles, Inversion of Control, and Dependency Injection, covers all SOLID principles, plus the inversion of Ccontrol and dependency injection libraries that come with ASP.NET Core and seperate NuGet packages.
Chapter 6, Data Access - Entity Framework with Repository, SQL Server, and Stored Procedures, covers implementing the repository pattern using Entity Framework Core. During implementation, we'll cover the IoC life cycle. Also, we'll investigate different providers of Entity Framework Core.
Chapter 7, Data Access with Micro ORMs, NoSQL, and Azure, covers creating DataAccessLayer with several libraries, such as Dapper and OrmLite. Also, we'll investigate MongoDB, Azure table storage, Azure blob storage, and SQL on Azure.
Chapter 8, Cache and Session - Distributed, Server, and Client, covers caching with several providers, such as InMemory Data Caching, Response Caching, Session Caching, and Distributed Caching. We'll use Redis on both on-premises and Azure.
Chapter 9, Routing, discusses the different aspects of ASP.NET Routing mechanisms, Route Constraints, and SEO-friendly routing.
Chapter 10, ASP.NET Core MVC, covers ActionResult types, creating and using POCO controllers, and managing Exceptions.
Chapter 11, Web API, discusses managing content-negotiation, handling cross-domain requests, auto-documenting controllers and actions using Swagger, and testing actions.
Chapter 12, Filters, covers how to create, manage, and use Global Filters for injecting tasks before and after the execution of actions, such as logging, caching, controlling authentication, and authorization.
Chapter 13, Views, Models, and ViewModels, covers creating and using ViewModels, and understanding and using the ModelBinding mechanism and ValueProviders.
Chapter 14, Razor and Views, talks about views, partial views, areas, HTML helpers, and dependency injection into views.
Chapter 15, TagHelpers and ViewComponents, dives deep into using Environment, Script, Form, and Link TagHelpers. We'll also create reusable ViewComponents.
Chapter 16, OWIN and Middlewares, describes OWIN and Katana, the new ASP.NET Core pipelines and middleware, along with creating and using ASP.NET Core middleware.
Chapter 17, Security, covers Authentication and Authorization mechanisms, managing Identity, and securing data with ASP.NET Core.
Chapter 18, Frontend Development, covers how to use Bootstrap classes, write maintainable and clean JavaScript code, and debug it. We will see what TypeScript is and write unit tests for JavaScript code.
Chapter 19, Deployment and Hosting, covers hosting ASP.NET Core web applications using IIS, Azure, and Docker. We'll also host ASP.NET web applications on Linux, Windows, and Mac environments using Kestrel.
It's beneficial to have some web backend or frontend programming experience.
You'll need Visual Studio 2017, Visual Studio Code, Atom, SQL Server Management Studio, and a modern web browser installed. Don't worry, we'll guide you on how to install them when needed.
You'll need an active Azure subscription. The Microsoft Azure platform offers free trial accounts at
http://www.azure.com
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/ASP.NET-MVC-Core-2.0-Cookbook. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/ASP.NETMVCCore2.0Cookbook_ColorImages.pdf.
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, use these sections as follows:
This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
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
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.
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.
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.
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.
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.
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.
Now in ASP.NET Core, every dependency and every DLL is a NuGet package that can be managed with dotnet CLI.
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
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.
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.
After installing .NET Core on Linux, creating a new project is easy.
Let's start creating a new project:
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
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
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:
In this recipe, we will learn how to create an ASP.NET Core MVC application on Linux with Docker, the new Container technology.
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.
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:
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
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
Add the current user to Docker group, then log out and log in again:
$ sudo usermod -aG docker $ sudo service docker restart
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.
Create a directory named
HelloWeb
, and place the two previous files inside.
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"]
Save and close
Dockerfile
.
Then, verify the existing containers (not mandatory):
$ sudo docker images
We can also check the running containers (not mandatory):
$ docker ps
You can build your application now:
$ docker build -t
Run it (port
5004
is the default port for Kestrel):
$ docker run -t -d -p 5004:5004
You can see the home page at
http:localhost:5004
.
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.
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.
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.
In this recipe, we will do the following:
Install
Homebrew
by entering this command at a Terminal:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Use
Homebrew
to get
DNVM
,
DNX
, and
DNU
using the commands as follows
:
$ brew tap aspnet/dnx $ brew update $ brew install dnvm $ source dnvm.sh
Install Node.js and npm (the npm will be installed automatically with Node.js):
$ brew install node
Verify Node.js and NPM versions:
$ node -v $ npm -v
The version currently being used will be displayed on your screen as follows:
Install
Yeoman
with
Gulp
to help automate tasks:
$ npm install -g yo gulp $ npm install -g generator-aspnet
Yeoman
asks us what type of application we want to create. In our case, we choose Web Application Basic.
After that,
Yeoman
asks us the name for the application to create, as shown in the following screenshot.
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.
With the command
cd "nameoftheapplication"
, we are placed in the application directory.
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:
Build and run
webapp1
typing the following command:
$ dotnet run
After executing the preceding command you get the following output at localhost:5000:
