【Chapter 3: Creating Minimal API Applications】

Chapter 1: Chapter 1: Foundations of Framework Learning and Practical Strategies

Chapter 2: Introduction to ASP.NET Core in Simple Terms

Chapter 3: Creating Minimal API Applications

  1. Overview of Minimal APIs
    In the vast landscape of ASP.NET Core, “Minimal API Applications” are akin to a lightweight yet powerful Swiss Army Knife, designed specifically for rapidly constructing HTTP APIs. These APIs inherently possess the capability to weave data into the JSON language, effortlessly engaging in intricate conversations with Single-Page Applications (SPAs) and swift interactions with mobile apps. They often collaborate with front-end stars (such as Angular, React.js, etc.) or mobile development platforms, jointly crafting seamless user experiences and efficient data flows.

Embarking on the journey of API creation in ASP.NET Core, Minimal APIs (Minimal APIs) seem to pave a high-speed lane for us. Compared to the traditional MVC or Razor Pages routes, it achieves a near-magical feat, enabling us to harness RESTful-style interfaces with mere snippets of code and configurations. Without getting entangled in the intricate weaving of controllers and view models, simply by crafting a series of fluent calls and skillfully arranging anonymous functions in the heart of the project, Program.cs, we can outline the blueprint of our API—from path planning to behavior definition, down to every detail of request handling.

What’s even more admirable is that Minimal APIs espouse a philosophy of “simplicity without simplicity.” It encourages us to discard traditional scaffolding rituals that may become burdensome, straightforwardly declaring the mission and functionality of APIs, rejecting redundant intermediate steps, leaving the program architecture as refreshing and efficient as a gentle breeze.

Minimal APIs are undoubtedly a shining star in ASP.NET Core, significantly lightening the load for developers with their remarkable simplification capabilities and flexibility, accelerating the processes of API creation, testing, and deployment, while ensuring code clarity and maintenance convenience. In .NET 6 and subsequent versions, this paradigm has received unprecedented reinforcement and promotion, becoming the preferred solution for constructing efficient, lightweight APIs.

Hey there, young ones! Don’t let those seemingly sophisticated terms intimidate you! In reality, they are all friendly companions in the digital world, and we should make them approachable and easy to understand.

First, “HTTP API” can be envisioned as a small post office on the internet. This post office operates under a set of special rules (i.e., the HTTP protocol), facilitating the exchange of letters (data and information) among different software buddies (like web pages, mobile apps, other servers, etc.). When you want to get something from or give something to one of these buddies, you send a request and receive a response through this digital post office.

Next, “SPA” is short for “Single-Page Application.” Imagine opening an incredibly powerful webpage that resembles a thick book, but you can view all its contents without flipping pages. An SPA is such a website where, after the initial load, subsequent content changes occur solely on this one page, eliminating the need to reload the entire page, akin to playing an ultra-smooth game.

As for “RESTful,” it’s not a religion! It’s an acronym for “Representational State Transfer,” which may sound complex but is essentially a design style, much like the way we organize our rooms. RESTful teaches us to envision web resources (like information on web pages) as books or boxes, and then use HTTP methods (GET, POST, PUT, DELETE) to manipulate these resources, just as we would pick up, put away, modify, or discard books from a bookshelf.

So, young ones, do these terms now seem more approachable? These companions in the digital world are all here to help us communicate, share, and work better.

  1. Basic Knowledge
    HTTP API functions as a “translator” in the digital world, using the universally understood language of the HTTP protocol to establish a set of communication rules. In this way, different software systems, such as web pages, mobile apps, other servers, etc., can send messages, request data, or issue instructions to each other through this “translator.”

Imagine that you (the client) want to borrow a book from the library (the server). You send a request to the library through the HTTP API “translator,” saying, “Hey, I want to borrow this book.” Upon receiving your request, the library (server) will search for the book as per your request and inform you whether it’s available or not—this is the response. The entire process is facilitated by the HTTP API “translator,” ensuring smooth communication between you and the library.

Characteristics of HTTP API:

Adheres to the HTTP Protocol: Just as there are dialing rules for making phone calls, HTTP API defines a set of standards for how to send requests and receive responses. For instance, using the GET method is akin to saying “give me this,” while the POST method is like saying “save this for me.”

RESTful Style: This is a popular communication approach that imagines everything on the web as books (resources), and manipulates these books through HTTP methods. For example, GET is used to read a book, POST to write a new book, PUT to modify a book, and DELETE to remove a book.

Stateless: Each interaction is independent, meaning the system does not remember what you did in the previous request unless you explicitly tell it. It’s like a library forgetting what books you borrowed last time unless you specify them again.

Ease of Use: HTTP APIs often come with a “user manual,” detailing how to send requests, which parameters to include, and what the responses look like, making it straightforward to get started.

Flexibility: You can choose to write requests and responses in different languages such as JSON, XML, and communicate via various methods, including synchronous and asynchronous, akin to choosing between writing letters, making phone calls, or video chatting.

The term “API” (Application Programming Interface) mentioned here refers to a software intermediary that defines a set of protocols, specifications, or standards, enabling communication and data exchange between different software applications. In short, APIs serve as the “bridges” between different software applications, allowing them to “talk” and “interact” with each other.

HTTP API is incredibly important in modern software development, as it enables different software systems to work seamlessly together and share data, much like children of various ethnicities and nationalities playing happily in the same playground.

Creating Your First Minimal API Application
Just like the straightforward and blunt Master Ke Zhen’e from the martial arts novel “Legend of the Condor Heroes,” he is known for his directness. His famous line, “Follow my lead,” often followed by a scene where he gets knocked down by an enemy, only to glare fiercely and shout, “Kill me if you must!” embodies this directness.
在这里插入图片描述
Launch Visual Studio 2022 and select “Create a new project (N).”

In the “Create a new project” dialog box:

Type “Empty” into the “Search for templates” search box.
Select the “ASP.NET Core Empty” template, and then choose “Next.”
在这里插入图片描述
在这里插入图片描述
In the “Configure your new project” dialog box, enter “BookQuerySystem” (you can name it as you like) for the “Project name,” choose a location (L) as desired, and click “Next.”
在这里插入图片描述
In the “Configure other information” dialog box, under Framework (F), select “.NET 8.0 (Long-term support)” and check the “Configure for HTTPS (H)” checkbox, then click “Create.”

After a few seconds, Visual Studio 2022 will create a project named BookQuerySystem using the default project template. This is a simple project. Next, press Ctrl+F5 to run it.

Pressing Ctrl+F5 starts the application without debugging, allowing you to make changes to the code, save files, and refresh the browser to see the updated page effects.

If the project is not configured to use SSL, Visual Studio will display a dialog box:

You can think of SSL as a super bodyguard dedicated to securing the transmission of information over computer networks. When you decide to use SSL to protect your data, this bodyguard goes to work, ensuring that your data is encrypted during transmission and reception, akin to putting an invisible protective layer on the data. This way, even if someone tries to snoop on or steal the data, they won’t be able to understand or take it due to the encryption, thereby safeguarding the data and preventing unauthorized disclosure.

If you trust the IIS Express SSL certificate, select “Yes.”
If you agree to trust the development certificate, select “Yes.”
It’s okay if the above doesn’t make sense yet; just select “Yes” for now.
If the project is already configured to use SSL, no dialog box will appear.

Additionally, we can also start the application in debug or non-debug mode from the “Debug” menu.

(Note: The last sentence is repeated, but I’ve included it as per your request to maintain the original text.)
在这里插入图片描述
The following image shows the application running on the Microsoft Edge browser!
在这里插入图片描述
What do you see? Is it the classic “Hello World!”? I bet not, what we have here is our old friend, the BookQuerySystem project, and this time we’ve dug an even bigger hole! But fear not, I have faith that together we can fill this technical hole with our collective efforts.

Perhaps this is your very first application you’ve built from scratch, and even if you haven’t typed a single line of code yet, you deserve a big thumbs up for taking the first step towards success! Who says programming has to be a tedious learning experience? Not us! We want to learn with joy and excitement. Let’s laugh, chat, and enjoy the thrill of creation together on this programming journey!

Diving Deeper into Minimal APIs
We briefly mentioned earlier that in the world of ASP.NET Core, there’s a new kid on the block called “Minimal APIs.” It’s like a super-streamlined API development powerhouse, designed to help us build web applications faster and easier. It represents a new model for building APIs with ASP.NET Core.
So, what exactly are Minimal APIs?

Minimal APIs are a new feature introduced in ASP.NET Core starting from version 6.0. They employ a functional programming approach, using a series of commands to set up routes, handle requests, and middleware, all in a very straightforward manner, without the complexity of controllers and action methods. Don’t worry if concepts like routes, request handling, and middleware are still unclear; we’ll cover them in detail later.

Why do we need Minimal APIs?

Microsoft introduced Minimal APIs to make developing web applications simpler and more efficient. They eliminate a lot of the traditional boilerplate code, making your code cleaner and development faster.

What are the benefits of Minimal APIs?

Less Code: Without controllers and action methods, there’s naturally less code, making it simpler to understand.
Fewer Dependencies: No need for additional NuGet packages; just use the ones that come with ASP.NET Core, keeping your project cleaner.
Intuitive Routing Configuration: Setting up routes with chained calls is easy to grasp and get started with.
Lightweight Applications: With less code and fewer dependencies, your applications start faster and use less memory.
When should you use Minimal APIs?

Minimal APIs are ideal when you need to quickly build a small, focused Web API or when constructing services within a microservices architecture. They allow you to complete tasks efficiently and with speed.
Let’s take a look at the simplest Minimal API example we just created:

// First, we create a builder for our web application
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Then, we use the builder to construct the application
WebApplication app = builder.Build();

// Next, we use the MapGet method to set up a route. When the root URL (/) is accessed, it returns a "Hello World!"
app.MapGet("/", () => "Hello World!");

// Finally, we start the application
app.Run();

In this example, we have created a web application and set up a simple route that responds with “Hello World!” whenever someone visits the root URL of the application.

Let’s break down the code line by line:

// First, we create a builder for our web application
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

In the .NET world, especially when using ASP.NET Core or newer versions of .NET (such as .NET 8.0 and above, which this text assumes), the WebApplication class contains a highly useful method called CreateBuilder(args). This method returns a WebApplicationBuilder instance (here named ‘builder’), which acts as the “contractor” for building your web application. It initiates the construction process, allowing you to set up your application, manage dependencies, configure logging, add middleware, and more.

Think of the “Builder” pattern as a step-by-step process of adding bricks and mortar to build a house. In the world of WebApplicationBuilder, you don’t need to gather all the materials at once; you can add them as you go, resulting in cleaner, more organized code. WebApplication.CreateBuilder(args) is a crucial step in ASP.NET Core for initializing and configuring your web application, offering flexibility and convenience in building and configuring your modern web apps, akin to playing Minecraft.

Specifically, WebApplication.CreateBuilder(args) performs several significant tasks:

Initializing the “Waiter”: It first identifies a “waiter” (dependency injection container) responsible for providing necessary “services” (like database connections, utility classes) to other parts of the application.
Setting Up the Logbook: It prepares a logbook so that you can record information, warnings, or errors throughout different parts of your application.
Configuring the House and Furniture: It configures the “house” (the web application’s host) and “furniture” (application configurations), including selecting the “address” (URL) to access your application and choosing the “decorating company” (like the Kestrel server) to run your website.
Offering Customization: It also provides ample opportunities for customization, allowing you to specify additional “services” (service configurations), logging preferences, and more.
Completing the Construction: While WebApplicationBuilder itself doesn’t directly run the application, it has a Build() method that constructs a WebApplication instance (named ‘app’), which is used to actually run your web application.

// Then, we use the builder to construct the application
WebApplication app = builder.Build();

In ASP.NET Core (starting from .NET 6.0), the MapGet method is a powerful tool. It instructs the program: “Hey, if someone visits this specific URL (like the root directory of your website) using the GET method, execute this piece of code and tell the visitor ‘Hello World!’.”
Looking at this line of code:

app.MapGet("/", () => "Hello World!");

It accomplishes three straightforward tasks:

Setting the URL: It uses the “/” symbol to indicate: “I’m setting up the URL for the root directory of the website.” This means that whenever the root directory of the website is accessed, either by directly typing the URL or clicking a link on the homepage, this code will come into play.
Writing the Response: It then defines a small function: “() => ‘Hello World!’”. This function acts like an automatic reply machine with no complex parameters. When someone visits, it simply responds with “Hello World!”.
Adding to the Processing Pipeline: The MapGet method effectively places this small function into a place called the “request processing pipeline.” Imagine this pipeline as a gatekeeper for the website, responsible for examining each incoming request. When it detects a GET request to the root directory, it locates this function and uses it to respond to the visitor.
Moreover, although here it simply responds with a text message, ASP.NET Core is smart enough to automatically wrap this text into an HTML page for the visitor and tell the browser that the content is plain text (text/plain). If you want to send HTML, JSON, or other content, you can also instruct ASP.NET Core how to do so.

In essence, this line of code tells ASP.NET Core: “If someone visits the homepage of the website, please respond with ‘Hello World!’.”

// Finally, start the application
app.Run();

The role of app.Run() is straightforward. It’s like telling ASP.NET Core: “Hey, I’ve prepared everything for the website, including how to handle different webpage requests, how to interact with the database, and so on. Now, please open the ‘gate’ of the website and start accepting visitors from the outside!” Here, the “gate” refers to the HTTP server, which is responsible for receiving requests from the internet and processing them according to our predefined rules. So, app.Run() is the command that presses the “open the gate” button.

The “HTTP server” we mentioned is like the super-efficient “receptionist” behind the ASP.NET Core website – Kestrel. Kestrel is impressive in that it works cross-platform, seamlessly handling websites built on Windows, Linux, or macOS. Its primary job is to stand by, waiting to receive various requests from the internet and processing them according to our previously established rules.

In fact, when you prepare your website and tell ASP.NET Core, “Hey, I’m ready to welcome visitors!”, Kestrel, the “receptionist,” automatically steps forward to do its job, which is to open the “gate” and greet those incoming HTTP requests from the internet. While the app.Run() command is often implicit in the Minimal APIs world, it serves as the signal that tells Kestrel, “It’s time to stand guard.” In the end, when we say “Please open the ‘gate’ of the website,” we’re instructing Kestrel, the super “receptionist,” to start its work of receiving and processing HTTP requests from all directions.

Next, let’s run the application again by pressing Ctrl+F5:
在这里插入图片描述
The URL https://localhost:7260/ acts like a key that unlocks a specific “door” on your computer. Let me break down the different parts of this URL into simpler terms:

Protocol Part (https://): This is like the route you take to get to a place. Here, the route is the “secure webpage route,” which is HTTPS. It’s like putting a password lock on your data transmission, ensuring that no one can sneak a peek at the information you send or receive.

Hostname (localhost): This is like the name of the shop you’re going to, but with a special twist – it actually refers to your own computer. So, you don’t need to go online to find it; you can directly access this “shop” on your computer.

Port Number (:7260): Imagine each “shop” has many different rooms, each with its own door number. Here, 7260 is the “door number” of that specific “room.” It tells your computer, “Hey, I’m looking for the service listening on room number 7260.”

Path (/): This is like knowing where the item you’re looking for is located once you’re inside the “shop.” The “/” here represents the starting point, the entrance to that “room,” or the default display area in the shop.

Putting it all together, https://localhost:7260/ tells your computer, “Please use the secure webpage route to access the service listening on port 7260 of my computer and show me the default content.” This content could be a website you’re developing, an API endpoint, or the “home” of any web service or application on your computer. Since it’s on your own computer, this URL is exclusive to you, and others cannot access it unless you grant them permission.

Now that you’ve crossed the threshold of adventure, let’s see what treasures lie within. Apparently, we’re building a book search system, so let’s check if there are any books inside. In the address bar of your browser, type in the URL https://localhost:7260/Books and hit Enter to take a look.
在这里插入图片描述
Wow! We’ve opened that mysterious door, only to find a little twist waiting for us – an error! But it’s all part of the adventure to solve problems, right?
在这里插入图片描述

Imagine walking into an empty room (with the door number “/”), and there’s nothing inside, right? So, when you try to find a book, specifically one on a shelf labeled “Books,” you won’t find it because there’s no shelf, and definitely no shelf labeled “Books” in that room.

Similarly, when you enter https://localhost:7260/Books in your browser to access the “Books” page on your website, because you haven’t put anything related to “Books” behind the door of “/”, the server will tell you, “Oops, I can’t find the page you’re looking for!” Then, it displays a 404 error page, which is like the server saying, “Sorry, you’ve knocked on the wrong door. There’s nothing here for you.”

This 404 error page is automatically generated by the server to inform you, “The requested resource does not exist.” This way, you know to check if the URL is typed incorrectly or if the website administrator hasn’t added what you’re looking for yet.

In the next chapter, we’ll guide you step-by-step in building a book search system, explaining each concept clearly so that you understand how everything fits together, just like following a recipe to create a delicious dish. It’s getting late, so let’s call it a day and rest up for more adventures tomorrow!

相关推荐

  1. csapp-chapter3--mov指令

    2024-07-15 15:22:01       48 阅读
  2. C++基础练习 - Chapter 3

    2024-07-15 15:22:01       19 阅读
  3. Chapter 1 - 3. Introduction to Congestion in Storage Networks

    2024-07-15 15:22:01       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-15 15:22:01       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-15 15:22:01       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-15 15:22:01       62 阅读
  4. Python语言-面向对象

    2024-07-15 15:22:01       72 阅读

热门阅读

  1. 【TypeScript】 泛型(Generics)

    2024-07-15 15:22:01       17 阅读
  2. php file_get_contents https 请求 伪造user_agent

    2024-07-15 15:22:01       22 阅读