Book Image

Modern Web Development with ASP.NET Core 3 - Second Edition

By : Ricardo Peres
Book Image

Modern Web Development with ASP.NET Core 3 - Second Edition

By: Ricardo Peres

Overview of this book

ASP.NET has been the preferred choice of web developers for a long time. With ASP.NET Core 3, Microsoft has made internal changes to the framework along with introducing new additions that will change the way you approach web development. This second edition has been thoroughly updated to help you make the most of the latest features in the framework, right from gRPC and conventions to Blazor, which has a new chapter dedicated to it. You’ll begin with an overview of the essential topics, exploring the Model-View-Controller (MVC) pattern, various platforms, dependencies, and frameworks. Next, you’ll learn how to set up and configure the MVC environment, before delving into advanced routing options. As you advance, you’ll get to grips with controllers and actions to process requests, and later understand how to create HTML inputs for models. Moving on, you'll discover the essential aspects of syntax and processes when working with Razor. You'll also get up to speed with client-side development and explore the testing, logging, scalability, and security aspects of ASP.NET Core. Finally, you'll learn how to deploy ASP.NET Core to several environments, such as Azure, Amazon Web Services (AWS), and Docker. By the end of the book, you’ll be well versed in development in ASP.NET Core and will have a deep understanding of how to interact with the framework and work cross-platform.
Table of Contents (26 chapters)
Section 1: The Fundamentals of ASP.NET Core 3
Section 2: Improving Productivity
Section 3: Advanced Topics
Appendix A: The dotnet Tool

Making HTTP calls

One typical need in Blazor apps is to make HTTP calls. Think of AJAX-style (XMLHttpRequest or fetch) operations, which are the bread and butter of SPAs. For that, we need an HTTP client, and the most convenient one is HttpClient.

We first need to register the services for it in the ConfigureServices method (for the Server hosting model), as follows:


Then, we can inject the IHttpClientFactory service in our Blazor app, and from it build HttpClient, as illustrated in the following code snippet:

public IHttpClientFactory HttpClientFactory { get; set; }

HttpClient HttpClient => HttpClientFactory.CreateClient();

There are different overloads to AddHttpClient, for when we need to configure a named client with specific settings—default headers, timeouts—and then create that client in CreateClient, but I won't go through that here.

HttpClient can send POST, GET, PUT...