【Chapter 3: Creating Minimal API Applications】

Chapter 1: Foundations of Framework Learning and Practical Strategies

Chapter 2: An Introduction to ASP.NET Core in Layman‘s 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.

2. 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.

3.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!

4.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!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/46738.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Mysql表的三范式、事务和查询

数据表的三范式 在制定数据表,需要遵循的制表规范:第一范式(1NF),第二范式(2NF),第三范式(3NF) 第一范式 属性不可分割,每一个属性(每一个单元格)都是不可再分的原子,也就是说数据表中的每一个字段必须是单独一列的,不能出现还可以再拆分的情况,也可以说成是…

数电基础 - 半导体存储

目录 一. 简介 一. 只读存储器 二. 可编程只读存储器 三. 可擦除的可编程只读存储器 四. 随机存储器 五. 存储器容量的扩展 六. 总结 一. 简介 半导体存储是数字电路中用于存储数据的重要组成部分。 半导体存储器主要分为两大类:随机存取存储器&#xff0…

【人工智能】Transformers之Pipeline(二):自动语音识别(automatic-speech-recognition)

​​​​​​​ 目录 一、引言 二、自动语音识别(automatic-speech-recognition) 2.1 概述 2.2 技术原理 2.2.1 whisper模型 2.2.2 Wav2vec 2.0模型 2.3 pipeline参数 2.3.1 pipeline对象实例化参数​​​​​​​ 2.3.2 pipeline对象使用参数…

16001.WSL2 ubuntu20.04 编译安装 vsomeip

文章目录 1 vsomeip 编译安装1.1 vsomeip的安装1.2 编译提示错误1.3 编译hello_world示例1.4 运行服务器端 1 vsomeip 编译安装 1.1 vsomeip的安装 参考博文 https://blog.csdn.net/peterwanye/article/details/128386539 1.2 编译提示错误 ubuntu1-BJ-EE1000042:~/opt/vso…

Flask启动5000端口后关不掉了?

事情是这样的: 使用python app.py启动flask应用后,又启动了另一个flask测试应用,也能启动成功,也没有报设么端口冲突,关闭黑窗口后,访问还是有守护进程在运行, 为什么我知道5000还在运行&#…

深入理解缓冲区:提升程序性能的关键

深入理解缓冲区:提升程序性能的关键 1、什么是缓冲区?2、缓冲区的作用3、缓冲区在Java中的应用4、如何操作缓冲区5、总结 💖The Begin💖点点关注,收藏不迷路💖 缓冲区(Buffer)是一种…

2024Datawhale AI夏令营---基于术语词典干预的机器翻译挑战赛--学习笔记

#Datawhale #NLP 1.背景介绍: 机器翻译(Machine Translation,简称MT)是自然语言处理领域的一个重要分支,其目标是将一种语言的文本自动转换为另一种语言的文本。机器翻译的发展可以追溯到20世纪50年代,经历…

07:串口通信二

串口编程 1、与波特率之相关的寄存器2、PCON寄存器3、SCON寄存器4、配置的代码分析5、向PC发送一段字符串6、PC机向单片机发送字符控制LED1灯的亮灭 1、与波特率之相关的寄存器 如图,与串口通信相关的寄存器主要是SCON和PCON寄存器。 2、PCON寄存器 SMOD&#xff1…

信息素养大赛-2024-算法创意实践挑战复赛-小学组

文章目录 一、前言二、问题问题:玫瑰花地的面积问题:判断三角形问题:汤姆的日记问题:正方形的数量问题:字符操作问题:猴子摘桃 三、感谢 一、前言 本章节主要对2024年信息素养大赛算法创意实践挑战复赛小学…

通用图形处理器设计GPGPU基础与架构(三)

一、前言 前两篇已经介绍了 GPGPU 的背景 和 GPGPU 的编程模型相关的内容,本文将在 SIMT 计算模型的基础上,介绍 GPGPU 控制核心架构和微体系结构的设计。 二、CPU-GPGPU 异构计算系统 一个由 CPU 和 GPGPU 构成的异构计算平台如下图所示,GP…

开源AI智能名片S2B2C商城小程序:重塑营销一体化新生态,引领未来商业潮流!

在互联网时代,尤其是移动互联网的迅猛发展下,顾客的认知与购买行为发生了翻天覆地的变化。曾经,顾客的认知和购买是两个相对独立的过程,不仅时间不同步,空间上也存在明显的分离。但如今,微信、App、电子商务…

MATLAB中Simulink.SimulationData.Dataset用法

目录 语法 说明 示例 访问使用Dataset格式记录的数据 打开模型vdp 使用 Dataset 对象来组合模拟输入信号 Simulink.SimulationData.Dataset的功能是访问已记录的模拟数据或组合模拟输入数据。 语法 ds Simulink.SimulationData.Dataset ds Simulink.SimulationData.Da…

如何在gitee上创建远程仓库?

登录gitee网站后 填写自己的仓库信息后点击创建 然后来到一个新的界面可以看到自己的仓库地址 这样一个空白的仓库就建立好了 也可以按需选择初始化仓库

jmeter-beanshell学习10-字符串补齐位数

每天都遇到新问题,今天又一个场景,一个字符串,如果不足11位,则左边补0,补够11位。 先要获取字符串长度,然后计算差多少位,补齐。今天又发现一个Object类型,这个类型有点厉害&#x…

ARM 虚拟机FVP环境搭建

ARM Fixed Virtual Platforms (FVPs) 是由 ARM 提供的一系列虚拟化硬件模拟器,用于在物理硬件可用之前开发和测试软件。FVP 模型非常适用于软件开发、验证和性能分析,涵盖了从裸机到操作系统和复杂 SoC 系统的各种应用。 这里以Cortex-M55为例&#xff0…

【区块链 + 智慧政务】中国铁塔区块链委托代征开票应用 | FISCO BCOS应用案例

中国铁塔是全球规模最大的通信铁塔基础设施服务提供者。通信塔站址点多面广,业主构成复杂,因此产生海量税务、合同、票据等信息。为进一步提高场租或供电取票的及时性和规范性,严格遵循税务相关的要求,中国铁塔采用国产开源联盟链…

RHCSA —— 第五节 (Linux中执行命令)

目录 一、命令格式 命令 分为两种:内置命令 和 外部命令 选项:指定命令的运行特性,指明要运行命令中的哪一个功能代码。 参数:命令的作用对象,即命令对什么生效。 小技巧 二、ls 命令 (list&#xff0…

惠海H5112A降压恒流芯片IC 60V72V80V100V转24V36V48V多路共阳输出景观LED点光源

H5112A是一款外围电路简单的多功能平均电流型LED恒流驱动器,适用于5-90V电压范围的非隔离式大功率恒流LED驱动领域。芯片采用了平均电流模式控制,输出电流精度在士3%;输出电流对输入输出电压以及电感不敏感;芯片内部集成了环路补偿,外围电路更…

CV09_深度学习模块之间的缝合教学(4)--调参

深度学习就像炼丹。炉子就是模型,火候就是那些参数,材料就是数据集。 1.1 参数有哪些 调参调参,参数到底是哪些参数? 1.网络相关的参数:(1)神经网络网络层 (2)隐藏层…

AIGC笔记--基于Stable Diffusion实现图片的inpainting

1--完整代码 SD_Inpainting 2--简单代码 import PIL import torch import numpy as np from PIL import Image from tqdm import tqdm import torchvision from diffusers import AutoencoderKL, UNet2DConditionModel, DDIMScheduler from transformers import CLIPTextMod…