【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

Chapter 4 .NET 8.0 ASP.NET Core BookQuerySystem: Project Layout

Chapter 5: Middleware in .NET 8.0 ASP.NET Core Book Management System

3.1. Overview of Minimal APIs

In the vast landscape of ASP.NET Core, “Minimal API Applications” resemble a sleek and powerful Swiss Army Knife, specifically designed for rapidly building efficient HTTP APIs. These APIs inherently support serializing data into JSON format, adeptly handling intricate interactions with Single-Page Applications (SPAs) and instant communications with mobile apps. They collaborate closely with front-end leaders (such as Angular, React.js, etc.) or mobile development platforms to jointly craft seamless user experiences and efficient data flow environments.

Embarking on the API development journey with ASP.NET Core, Minimal APIs (Minimal APIs) undoubtedly pave a high-speed path for us. Compared to the traditional MVC or Razor Pages routes, it employs a near-magical approach, allowing us to effortlessly master RESTful-style interfaces with minimal code and configuration. Developers are freed from the intricate weaving of controllers and view models, instead, they can outline the blueprint of their APIs in the project’s core file, Program.cs, through a series of fluent calls and ingenious orchestration of anonymous functions—from path design to behavior definition, down to every detail of request processing.

Particularly noteworthy is that Minimal APIs adhere to the philosophy of “simple yet powerful.” It encourages developers to discard traditional scaffolding patterns that might become burdensome, directly and concisely declaring the functions and purposes of APIs, rejecting redundant steps, and leaving the program architecture crisp and efficient, akin to a refreshing breeze.

Minimal APIs undoubtedly stand out as a shining star in ASP.NET Core. Leveraging its remarkable simplification capabilities and flexibility, it significantly lightens the load on developers, accelerates the API creation, testing, and deployment processes, while ensuring code clarity and ease of maintenance. In .NET 6 and subsequent versions, this model has received unprecedented reinforcement and promotion, emerging as the preferred solution for building efficient, lightweight APIs.

3.2 Basic Knowledge

HTTP APIs play the role of “translators” in the digital world, utilizing the universal language of HTTP protocols to establish a set of interaction norms. This enables different software systems, such as web pages, mobile apps, other servers, etc., to send messages, request data, or issue instructions through HTTP APIs.

Imagine you, as a client, wish to borrow a book from a server (let’s say a library). You would send a request to the library through the HTTP API “translator,” saying, “Please lend me this book.” Upon receiving the request, the library would search for the book as instructed and inform you of its availability—this process constitutes the response. The entire interaction takes place through HTTP APIs, ensuring smooth communication between both parties.

The key features of HTTP APIs include:

  • Adherence to HTTP Protocols: Akin to dialing rules for phone calls, HTTP APIs stipulate standard formats for requests and responses. For instance, GET methods are used to request data, while POST methods are for submitting data.
  • RESTful Style: This popular resource manipulation approach treats network resources as books or boxes, performing CRUD operations (Create, Read, Update, Delete) through HTTP methods (GET, POST, PUT, DELETE).
  • Statelessness: Each interaction occurs independently, with the server not retaining the state of previous interactions unless explicitly informed.
  • Ease of Use: HTTP APIs typically provide documentation outlining how to send requests, which parameters to include, and the response formats, facilitating quick adoption.
  • Flexibility: Supporting multiple data formats (e.g., JSON, XML) and interaction modes (synchronous, asynchronous), catering to diverse needs and scenarios.

In modern software development, HTTP APIs occupy a pivotal position. They enable different software systems to collaborate effortlessly, sharing data, much like children of various ethnicities and nationalities playing happily in the same playground.

3.3 Creating Your First Minimal API Application

Like the straightforward characters in martial arts novels, Minimal APIs attract developers with their direct and efficient nature. Next, we will guide you through creating your first Minimal API application.

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:

SSL serves as a security guard for data transmission, encrypting data to protect its safety.

  • If you trust the IIS Express SSL certificate, select “Yes.”
  • If you agree to trust the development certificate, select “Yes.”
  • If you do not understand the content, simply select “Yes” for now.

If the project is already configured for SSL, the dialog box will not appear. You can also launch the application from the “Debug” menu in debug or non-debug mode.

Below is the running effect of the application in Microsoft Edge:

You will see the default response, “Hello World!”, but rest assured, this signifies that the BookQuerySystem project has successfully started.

The following image shows the application running on the Microsoft Edge browser!
在这里插入图片描述
Code in the Program.cs file:

// First, we create a builder for the web application    
// WebApplicationBuilder initializes the application and configures dependency injection, logging, etc.    
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);    
  
// Then, we use the builder to construct an application instance    
// The WebApplication instance is used to configure routes, middleware, etc., and ultimately run the application    
WebApplication app = builder.Build();    
  
// Set up a route to return "Hello World!" when the root URL is accessed    
// The MapGet method defines a route for GET requests and specifies the handling function    
app.MapGet("/", () => "Hello World!");    
  
// Finally, start the application    
// The app.Run() method starts the Kestrel server, beginning to listen and process HTTP requests    
app.Run();
3.4 Diving Deeper into Minimal APIs

In the ASP.NET Core architecture, “Minimal APIs” represent an innovative feature, renowned for its simplicity and efficiency since its introduction in version 6.0. It employs functional programming methods, setting up routes, handling requests, and middleware through a series of commands, avoiding the complexity of traditional controllers and action methods.

Why Minimal APIs?

Microsoft introduced Minimal APIs to streamline the Web application development process and enhance development efficiency. By reducing boilerplate code, it results in cleaner and more concise code, thereby accelerating development.

Advantages of Minimal APIs:

  • Code Reduction: Without controllers and action methods, the amount of code is significantly reduced.
  • Dependency Simplification: Only ASP.NET Core’s built-in packages are required, eliminating the need for additional NuGet packages.
  • Intuitive Routing Configuration: Routes are set up using chained calls, making them easy to understand and implement.
  • Lightweight Applications: With less code and dependencies, applications start faster and consume lower memory.

Applicable Scenarios:

When you need to rapidly build small, dedicated Web APIs or deploy services within a microservice architecture, Minimal APIs will be your trusty companion.

Example Analysis and Expansion:

In addition to the previous “Hello World” example, we can expand on a Minimal API example in a real-world scenario, such as creating a simple book information retrieval interface:

// Set up a route to return a list of books when /books is accessed
app.MapGet("/books", async () =>
{
    // Assuming a list of books, hardcoded for simulation purposes
    var books = new List<string> { "ASP.NET Core Programming", "C# in Depth" };
    return Results.Ok(books); // Use Results.Ok to return a 200 OK response with the book list
});
Summary

Through this chapter’s exploration, we have not only gained an understanding of the core concepts and practical applications of Minimal APIs but also witnessed their significant role in modern Web development. With its streamlined and efficient design philosophy, Minimal APIs simplify development processes, reduce complexity, and allow developers to focus more on business logic implementation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代数狂人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值