ray wikis encyclopedia

ASP.NET Core lets you build and run web apps on Windows, Linux, or macOS. This brings mixed blessingson the one hand, the ASP.NET 4.x framework today is a reliable, battle-tested platform for building modern applications on Windows. In the next section well create a Tag Helper that does need to know the content. IIS receives a request. .NET 5.0 and C# 9 introduced top-level statements, which implicitly create the Main entry point. ), but you should keep in mind how they follow on from each other and how they contribute to the applications configuration as a whole. Theyre built in a series of layers and dont require you to boot a new operating system when starting a new one. 4. Most ASP.NET Core applications have dependencies on various external libraries, which are managed through the NuGet package manager. Finally, youll learn how to test your applications using both unit tests and integration tests. He has been developing professionally using .NET for the last 10 years, using a wide range of technologies including WinForms, ASP.NET WebForms, ASP.NET MVC, and ASP.NET Webpages. Program is concerned with infrastructure configuration that will typically remain stable throughout the lifetime of the project. Figure 2.7 The Privacy page of your application. Copyright 2022 EBIN.PUB. We'll focus on building server-rendered applications using Razor Pages and Web APIs using MVC controllers. A naive approach to this problem is to use the new keyword and create an instance of a service whenever you need it. In the final configuration method of the Startup class, Configure, you define the middleware pipeline for the application, which defines how your app handles HTTP requests. Chapter 10 describes how to use ASP.NET Cores built-in dependency injection container to configure your applications services. Implicit file includes Previously, every file in the project had to be listed in the .csproj file for it to be included in the build.

4. You can read the chapters in part 3 out of order, though I recommend only doing so after you have covered parts 1 and 2. { public void Configure( Other services can be IApplicationBuilder app, accepted as parameters.

The Startup class: Configuring your application 47 The IWebHostEnvironment object contains details about the current environment, as determined by IHostBuilder in Program. The first of these steps isnt strictly necessary, as both Visual Studio and the .NET CLI automatically restore packages when they first create your project, but its good to know whats going on. DEFINITION 20 CHAPTER 1 Getting started with ASP.NET Core 1.

Chapter 23 shows how to test an ASP.NET Core application with the xUnit testing framework. The publisher offers discounts on this book when ordered in quantity.

This makes the class more flexible and enables you to modify the signature of the method to accept additional parameters that are fulfilled automatically. Instead, ExceptionHandlerMiddleware is registered so that if users encounter an exception in your method, they will be presented with a friendly error page that doesnt reveal the source of the problems. 1.1.2 What is ASP.NET Core? Conversely, the number of files can sometimes be overwhelming, leaving you scratching your head working out where to start. Microsoft provides a cross-platform web server by default, called Kestrel. Figure 2.3 The Configure Your New Project dialog box. Select ASP.NET Core 5.0. If you still have difficulties, see the troubleshooting tips at http://mng.bz/1rmy.

Chapter 17 shows how to configure logging in your application, and how to write log messages to multiple locations. Middleware placed afterwards can access the ClaimsPrincipal. For example, Windows-specific features like the Registry or Directory Services can be enabled with a compatibility pack that makes these APIs available in .NET 5.0.6 Theyre only available when running .NET 5.0 on Windows, not on Linux or macOS, so you need to take care that such applications only run in a Windows environment or account for the potential missing APIs. I dont use top-level statements in this book, but they are supported in ASP.NET Core 5.0. Entity Framework Core in Action, Second Edition is an in-depth guide to reading and writing databases with EF Core. This helper uses routing to generate the href URL using asp-page, asp-page-handler, and asp-route-* attributes, giving you the full power of routing. Select ASP.NET Core Web App. The endpoint middleware actually executes the Razor Page to generate the HTML response. In reality, youd update the message to something more user-friendly. By adding a new service to it, you ensure that whenever a class declares a dependency on your service, the IoC container knows how to provide it. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text.

Chapter 3 looks in detail at the middleware pipeline, which defines how incoming web requests are processed and how a response is generated. However, each iteration has been built on top of the .NET Framework, and so comes preinstalled in all versions of Windows. Whether you need a simple website, a complex e-commerce web app, or a distributed web of microservices, you can use your knowledge of ASP.NET Core to build lean web apps that fit your needs. For ASP.NET Core, Microsoft created a lightweight platform that runs on Windows, Linux, and macOS called .NET Core (and subsequently .NET 5.0), as shown in figure 1.3. Visual Studio uses the concept of a solution to work with multiple projects. Response passes through middleware back to the web server. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). The first time you run the application from Visual Studio, you will be prompted to install the development certificate.

Generating responses with Razor Pages 51 Figure 2.14 Rendering a Razor template to HTML. When to choose ASP.NET Core 9 By adding an ASP.NET Core web server to your .NET 5.0 app, your application can run as a web application.

You dont need to know any JavaScript or CSS frameworks for this book, though ASP.NET Core works well with both if that is your forte. Not all browsers (Mozilla Firefox, for example) use the certificate store, so follow your browsers guidelines for trusting the certificate. Additionally, comments in the source code have often been removed from the listings when the code is described in the text.

by using the Validation Message Tag Helper. ASP.NET Core let developers leverage their existing knowledge of the .NET framework, and of ASP.NET MVC applications xix xx PREFACE in particular, while baking in current best practices like dependency injection, strongly typed configuration, and logging.

For an introduction to Markdown, see the GitHub guide: https://guides .github.com/features/mastering-markdown/. Whether you use Visual Studio or the .NET CLI, you now have the basic files required to build and run your first ASP.NET Core application. Well have a closer look at this project file in the next section.

Its equivalent to Ruby Gems, npm for JavaScript, or Maven for Java. You can store your CSS, JavaScript, images, or static HTML files in here and browsers will be able to access them. The Solution Explorer shows your newly created project. If this option isnt available, ensure you have .NET 5.0 installed. Chapter 20 expands on chapter 19 and shows how to build custom Razor Page components, such as custom Tag Helpers and custom validation attributes. 648 CHAPTER 20 Listing 20.3 Building custom MVC and Razor Pages components Using a Markdown Tag Helper in a Razor Page @page @model IndexModel The Markdown Tag Helper is added using the element. Ensure the authentication scheme is set to No Authentication. Well, yes and no! When you run it from Visual Studio, IIS Express chooses a random port by default.

How does ASP.NET Core work? Ideally, you will read the book cover to cover and then use it as a reference, but I realize that wont suit everyone. When I first began looking into ASP.NET Core, I was one of those developers. There are merits to both approaches, but I wanted to ensure the focus remained on the specific topics being taught, without the mental overhead of navigating an increasingly large project. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.

2.5 The .csproj project file: Defining your dependencies The .csproj file is the project file for .NET applications and contains the details required for the .NET tooling to build your project. I assume a passing familiarity with HTML and CSS and of JavaScripts place as a client-side scripting language. .NET Framework isnt being removed, so your old applications will continue to work, but you shouldnt use it for new development. NOTE Phew! By now, you should have a good idea of what ASP.NET Core is and the sort of applications you should use it for. In sections 2.6 and 2.7, youll see how these fundamental classes are responsible for configuring and running your application. It contains all the core code that ASP.NET uses when you build a web application. I also dont cover all the new features in .NET 5.0 such as Blazor and gRPC. Thanks also to Deirdre Hiam, my project editor; Andy Carroll, my copyeditor; Jason Everett, my proofreader; and Mihaela Batinic, my reviewing editor. In addition, it has many powerful features, such as Language Integrated Query (LINQ), closures, and asynchronous programming constructs.

TIP NuGet packages and the .NET command-line interface One of the foundational components of .NET 5.0 cross-platform development is the .NET command-line interface (CLI). The single responsibility principle (SRP) states that every class should be responsible for only a single piece of functionalityit should only need to change if that required functionality changes. Finally, thanks to all those friends who encouraged and supported me, and showed interest generally. Theres generally no point running other Tag Helpers if the element is going to be removed from the page anyway. 7. Figure 2.4 The web application template screen. Just as desktop or mobile development frameworks can help you build native applications, ASP.NET Core makes writing web applications faster, easier, and more secure than trying to build everything from scratch. The restore process typically happens implicitly when you build or run your application, but it can sometimes be useful to run it explicitly, in continuous-integration build pipelines, for example. You can publish (and host) NuGet packages to repositories other than https://nuget.orgsee https://docs.microsoft.com/nuget for details. 2 See chapter 18 for more about HTTPS certificates. Figure 2.11 The developer exception page contains many different sources of information to help you diagnose a problem, including the exception stack trace and details about the request that generated the exception.

The project file has been a mainstay of .NET applications, but in ASP.NET Core it has had a facelift to make it easier to read and edit. The ASP.NET Core framework code then calls into your handlers which, in turn, call methods in your applications business logic, as shown in figure 1.1. In this section, youll see how an application built with ASP.NET Core works, from the user requesting a URL to a page being displayed in the browser. REST stands for representational state transfer. What I saw at that point really impressed me. 21 1.4 19 What you will learn in this book 23 vii How does ASP.NET CONTENTS viii 2 Your first application 2.1 2.2 25 A brief overview of an ASP.NET Core application 26 Creating your first ASP.NET Core application 29 Using a template to get started 2.3 2.4 2.5 2.6 2.7 29 Building the application Running the web application 34 Understanding the project layout 35 The .csproj project file: Defining your dependencies The Program class: Building a web host 39 The Startup class: Configuring your application 42 Adding and configuring services 44 are handled with middleware 45 2.8 37 Defining how requests Generating responses with Razor Pages 50 Generating HTML with Razor Pages with PageModels and handlers 53 3 32 51 Handling request logic Handling requests with the middleware pipeline 58 3.1 3.2 What is middleware? When to choose ASP.NET Core 11 ASP.NET Core isnt restricted to creating RESTful services. When to choose ASP.NET Core 13 language, it provides a sense of familiarity to those used to C, Java, and many other languages. These changes include No GUIDsPreviously, globally unique identifiers (GUIDs) were used for many things, but now theyre rarely used in the project file. Each call configures a different part of your application, making it available for subsequent method calls. Figure 2.8 The Solution Explorer and folder on disk for a new ASP.NET Core application. That history provided the basis and impetus for the development of ASP.NET Core. DEFINITION Well use the popular Markdig library (https://github.com/xoofx/markdig) to create the Markdown Tag Helper. Microsoft created ASP.NET Core to be an additional layer on top of console applications, such that converting to a web application involves adding and composing libraries, as shown in figure 1.4. The first command, dotnet restore, ensures your applications NuGet dependencies are copied to your project folder. 20.1.3 Creating a Tag Helper to convert Markdown to HTML The two Tag Helpers shown so far are agnostic to the content written inside the Tag Helper, but it can also be useful to create Tag Helpers that inspect, retrieve, and modify this content. The IHost is the core of your ASP.NET Core application, containing the application configuration and the Kestrel server that listens for requests and sends responses. When rendered, the template in listing 7.2 would produce the following HTML. The hosting model for the previous ASP.NET framework was a relatively complex one, relying on Windows IIS to provide the web server hosting. I would have never been in a position to write this book if it werent for the excellent content produced by the .NET community and those I follow on Twitter. As youll see shortly, you can use Razor Pages in your application to define these two pages and build the HTML they display. The Validation Summary Tag Helper is applied to a , normally at the top or bottom of the form.

Create a Razor Pages project in a subfolder, WebApplication1. The hostname of a website uniquely identifies its location on the internet by mapping via the Domain Name Service (DNS) to an IP address. For example, for a request to www.microsoft.com/account/ manage, the path is /account/manage. Tanya Wilke verified that the code I wrote actually ran and made sense, working through the chapters with formidable efficiency. Recently used templates are shown on the left. NuGet is a package manager for .NET that enables importing libraries into your projects. In chapter 22 youll see how to build applications using the generic host to run scheduled tasks and build services. With .NET 5.0 alone, its possible to build console applications that run crossplatform. Obviously, youd need to update this page to be more visually appealing and more user-friendly, but at least it doesnt reveal the inner workings of your application. Doing so ensures your browser doesnt display warnings about an invalid certificate. Once the application is configured, it can start handling requests. To get there, first youll see how an HTTP request works for any web server, and then youll see how ASP.NET Core extends the process to create dynamic web pages. Listing 2.1 Creating a new Razor Page application with the .NET CLI dotnet new sln -n WebApplication1 dotnet new webapp -o WebApplication1 dotnet sln add WebApplication1 Add the new project to the solution file. 2.7.2 Defining how requests are handled with middleware So far, in the IHostBuilder and Startup classes, youve defined the infrastructure of the application and registered your services with the IoC container. Microsoft is recommending that all new .NET web development should use ASP.NET Core, but switching to or learning a new web stack is a big ask for any developer or company. 1.2.4 Converting an existing ASP.NET application to ASP.NET Core In contrast with new applications, an existing application is presumably already providing value, so there should always be a tangible benefit to performing what may amount to a significant rewrite in converting from ASP.NET to ASP.NET Core. This will check for any errors in your application and, if there are no issues, will produce output that can be run using dotnet run. 1.3.1 How does an HTTP web request work? Many developers have updated their libraries to work with ASP.NET Core, and many other libraries have been created to target ASP.NET Core specifically. In later parts of this book well dive deeper into the ASP.NET Core framework, where youll learn how to configure your application and add extra features, such as user profiles. Figure 2.5 Visual Studio after creating a new ASP.NET Core application from a template. To see the full list of available commands, run dotnet --help or to see the options available for a particular command, new for example, run dotnet new --help 34 2.3 CHAPTER 2 Your first application Running the web application Youre ready to run your first application, and there are a number of different ways to go about it. Chapter 5 describes the Razor Pages routing system. Application_AuthorizeRequest (){} Application_ProcessRequest() {} Application_EndRequest() {} Control transfers back and forth between IIS and ASP.NET as events are raised. See chapter 18 for details about this and other security-related middleware. Ensure No Authentication is specified.

Brian Sawyer discovered me in the first version of this book and encouraged me to tackle the second version. The middleware pipeline is defined in code in Startup. Within this top-level folder, youll also find the solution (.sln) file for use by Visual Studio and files related to Git version control,3 though these are hidden in Visual Studios Solution Explorer view. Visual Studio will update the project file itself, as it always has.

The first version of ASP.NET was released in 2002 as part of .NET Framework 1.0, in response to the then conventional scripting environments of classic ASP and PHP. The routing middleware selects an endpoint based on the request URL and application's route templates. This library is part of .NET Framework, so it comes pre-installed with all versions of Windows. In this section Id like to thank everyone who encouraged me, contributed, and put up with me for the past year. This dependency brings both advantages and disadvantages. The first major release of the framework in June 2016 still had many rough edges, in particular around the tooling experience.

Once Visual Studio has finished, youll be presented with an introductory page about ASP.NET Core, and you should be able to see that Visual Studio has created and added a number of files to your project, as shown in figure 2.5. Appendix B provides some background to .NET 5.0, .NET Core, and .NET Standard, discusses how they fit in the .NET landscape, and explains what they mean for your apps. Youll rarely find that you need to modify Program as your application grows, whereas youll normally update Startup whenever you add additional features. The ASP.NET Core framework code handles requests from a client, dealing with the complex networking code. If you run the default template in production mode and trigger an error, youll be presented with the message shown in figure 2.12 instead. Program.cs and Startup.cs control the startup and configuration of your application at runtime.

This book guides you through building your first applications, introducing additional complexity as you cement previous concepts. ASP.NET Core promised to change all that, allowing me to develop natively on both my Windows machine and my Mac. The .csproj file contains all the details required to build your project, including the NuGet packages used by your project. This allows the authorization middleware to decide whether to allow access before the Razor Page is executed. Before you can build and run your application, you need to ensure there are local copies of each dependency in your project folder. 16 CHAPTER 1 Getting started with ASP.NET Core line, though it doesnt necessarily remove the need to run IIS (or equivalent) in production, as youll see in section 1.3. 32 CHAPTER 2 An introductory page is shown when your project is first created. Listing 8.4. by using the asp-validation-for attribute: element will also be used to show appropriate validation messages if serverside validation fails and the form is being redisplayed. Be the first to receive exclusive offers and the latest news on our products and services directly in your inbox. Use the asp-validation-summary attribute to attach the Validation Summary Tag Helper to a .

public void Configure(IApplicationBuilder app) { Configure the middleware // method details pipeline for handling } HTTP requests. }

Once configuration is complete, the IHost is created by calling Build() on the HostBuilder. Its a completely separate platform, rather than a fork of .NET Framework, though it uses similar code for many of its APIs. For example, to install the popular Newtonsoft.Json library, you would run dotnet add package Newtonsoft.Json This adds a reference to the latest version of the library to your project file, as shown next, and makes the Newtonsoft.Json namespace available in your source code files. When .NET Core was originally released, there were few third-party libraries available for building these types of complex applications. Middleware can only use objects created by earlier middleware in the pipeline.

TIP In ASP.NET Core applications, the Main entry point is used to build and run an IHost instance, as shown in the following listing, which shows the default Program.cs file. It defines the type of project being built (web app, console app, or library), which platform the project targets (.NET Core 3.1, .NET 5.0, and so on), and which NuGet packages the project depends on. I provide as much context as possible, and I include links to sites and books where you can learn more. ray wikis encyclopedia