Reader small image

You're reading from  C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition

Product typeBook
Published inNov 2023
PublisherPackt
ISBN-139781837635870
Edition8th Edition
Right arrow
Author (1)
Mark J. Price
Mark J. Price
author image
Mark J. Price

Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years' experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET. Mark holds a Computer Science BSc. Hons. Degree.
Read more about Mark J. Price

Right arrow

Building and Consuming Web Services

This chapter is about learning how to build web services (aka HTTP or Representational State Transfer (REST) services) using the ASP.NET Core Web API. You will then learn how to consume web services using HTTP clients, which could be any other type of .NET app, including a website or a mobile or desktop app.

This chapter requires the knowledge and skills that you learned in Chapter 10, Working with Data Using Entity Framework Core, and Chapters 12 to 13, about building websites using ASP.NET Core.

In this chapter, we will cover the following topics:

  • Building web services using the ASP.NET Core Web API
  • Creating a web service for the Northwind database
  • Documenting and testing web services
  • Consuming web services using HTTP clients

Building web services using the ASP.NET Core Web API

Before we build a modern web service, we need to cover some background to set the context for this chapter.

Understanding web service acronyms

Although HTTP was originally designed to request and respond with HTML and other resources for humans to look at, it is also good for building services.

Roy Fielding stated in his doctoral dissertation, describing the REST architectural style, that the HTTP standard would be good for building services because it defines the following:

  • URIs to uniquely identify resources, like https://localhost:5151/api/products/23.
  • Methods for performing common tasks on those resources, like GET, POST, PUT, and DELETE.
  • The ability to negotiate the media type of content exchanged in requests and responses, such as XML and JSON. Content negotiation happens when the client specifies a request header like Accept: application/xml,*/*;q=0.8. The default response format used by...

Creating a web service for the Northwind database

Unlike MVC controllers, Web API controllers do not call Razor views to return HTML responses for website visitors to see in browsers. Instead, they use content negotiation with the client application that made the HTTP request to return data in formats such as XML, JSON, or X-WWW-FORM-URLENCODED in their HTTP response, which looks like the following:

firstName=Mark&lastName=Price&jobtitle=Author

The client application must then deserialize the data from the negotiated format. The most used format for modern web services is JavaScript Object Notation (JSON) because it is compact and works natively with JavaScript in a browser when building Single-Page Applications (SPAs) with client-side technologies like Angular, React, and Vue.

We will reference the Entity Framework Core entity data model for the Northwind database that you created in Chapter 12, Introducing Web Development Using ASP.NET Core:

  1. In the...

Documenting and testing web services

You can easily test a web service by making HTTP GET requests using a browser. To test other HTTP methods, we need a more advanced tool.

Testing GET requests using a browser

You will use Chrome to test the three implementations of a GET request—for all customers, for customers in a specified country, and for a single customer using their unique customer ID:

  1. Start the Northwind.WebApi web service project using the https launch profile.
  2. Start Chrome, navigate to https://localhost:5151/api/customers, and note the JSON document returned, containing all 91 customers in the Northwind database (unsorted), as shown in Figure 14.2:

Figure 14.2: Customers from the Northwind database as a JSON document

  1. Navigate to https://localhost:5151/api/customers?country=Germany and note the JSON document returned, containing only the customers in Germany.

    If you get an empty array returned, then make...

Consuming web services using HTTP clients

Now that we have built and tested our Northwind service, we will learn how to call it from any .NET app using the HttpClient class and its factory.

Understanding HttpClient

The easiest way to consume a web service is to use the HttpClient class. However, many people use it wrongly because it implements IDisposable and Microsoft’s own documentation shows poor usage of it. See the book links in the GitHub repository for articles with more discussion of this.

Usually, when a type implements IDisposable, you should create it inside a using statement to ensure that it is disposed of as soon as possible. HttpClient is different because it is shared, reentrant, and partially thread-safe.

The problem has to do with how the underlying network sockets must be managed. The bottom line is that you should use a single instance of it for each HTTP endpoint that you consume during the life of your application. This will allow each...

Practicing and exploring

Test your knowledge and understanding by answering some questions, getting some hands-on practice, and exploring this chapter’s topics with deeper research.

Exercise 14.1 – Test your knowledge

Answer the following questions:

  1. Which class should you inherit from to create a controller class for an ASP.NET Core Web API service?
  2. When configuring an HTTP client, how do you specify the format of data that you prefer in the response from the web service?
  3. What must you do to specify which controller action method will be executed in response to an HTTP request?
  4. What must you do to specify what responses should be expected when calling an action method?
  5. List three methods that can be called to return responses with different status codes.
  6. List four ways that you can test a web service.
  7. Why should you not wrap your use of HttpClient in a using statement to dispose of it when you are finished even though...

Summary

In this chapter, you learned:

  • How to build an ASP.NET Core Web API service that can be called by any app on any platform that can make an HTTP request and process an HTTP response.
  • How to test and document web service APIs with Swagger.
  • How to consume services efficiently.
  • How to build a basic HTTP API service using Minimal APIs.

In the next chapter, you will learn how to build user interfaces using Blazor, Microsoft’s component technology that enables developers to build client-side SPAs for websites using C# instead of JavaScript, and PWAs or hybrid apps for desktop.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781837635870
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime

Author (1)

author image
Mark J. Price

Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years' experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET. Mark holds a Computer Science BSc. Hons. Degree.
Read more about Mark J. Price