如何在 ASP.NET Core 中构建轻量级服务
在 ASP.NET Core 中处理 Web 应用程序时,我们可能经常希望构建轻量级服务,也就是没有模板或控制器类的服务。
轻量级服务可以降低资源消耗,而且能够提高性能。我们可以在 Startup 或 Program 类中创建这些轻量级服务或 API。
1. 使用 VS2022 创建 ASP.NET Core 项目
我们在 Visual Studio 2022 中创建一个 ASP.NET Core 项目。按照以下步骤在 Visual Studio 2022 中创建一个新的 ASP.NET Core Web API 6 项目。
- 1) 启动 Visual Studio 2022 IDE。
- 2) 单击 “Create new project”。
- 3) 在 “Create new project” 窗口中,从显示的模板列表中选择 “ASP.NET Core Web API”。
- 4) 点击下一步。
- 5) 在 “Configure your new project” 窗口中,指定新项目的名称和位置。
- 6) 根据您的偏好,可选择选中 “Place solution and project in the same directory” 复选框。
- 7) 点击下一步。
- 8) 在接下来显示的 “Additional Information” 窗口中,从顶部的下拉列表中选择 .NET 6.0 作为目标框架。将 “Authentication Type” 保留为 “None”(默认)。
- 9) 确保未选中 “Enable Docker,”、“Configure for HTTPS” 和 “Enable Open API Support” 复选框,因为我们不会在此处使用任何这些功能。您也可以选择取消选中 “Use controllers(取消选中以使用最少的 API)” 复选框,因为我们将创建自己的控制器。
- 10) 单击创建。
这将在 Visual Studio 2022 中创建一个新的 ASP.NET Core 6 Web API 项目。我们将在本文的后续部分中使用该项目,来说明如何使用轻量级服务。
2. 在 ASP.NET Core 中启用一个轻量级的服务
由于我们将构建不需要控制器的轻量级服务,所以应该删除 Controllers solution 文件夹和默认创建的任何模型类。
接下来,打开 Properties solution 文件夹下的 launchSettings.json 文件,删除或注释掉 launchUrl 键值对,如下面给出的代码所示。
其中,launchUrl 是指应用程序的主机。当应用程序启动时,launchURL 中指定的 URL 用于启动应用程序。
如果 URL 错误或不存在,应用程序将在启动时抛出错误。通过删除 launchUrl 或将其注释掉,我们可以确保应用程序不使用默认的 launchUrl 来启动应用程序,从而避免任何错误。一旦 launchUrl 被删除,应用程序将回到 5000 端口。
"profiles": {
"Light_Weight_Services": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
//"launchUrl": "",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
//"launchUrl": "",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
3. 在 ASP.NET Core 中使用 IEndpointConventionBuilder 扩展方法
我们可以利用 IEndpointConventionBuilder 接口的一些扩展方法来映射请求。
以下是这些扩展方法的列表:
- MapGet
- MapPost
- MapDelete
- MapPut
- MapRazorPages
- MapControllers
- MapHub
- MapGrpcServices
MapGet、MapPost、MapDelete 和 MapPut 方法用于将请求委托连接到路由系统。MapRazorPages 用于 RazorPages,MapControllers 用于 Controllers,MapHub 用于 SignalR,MapGrpcService 用于 gRPC。
以下代码说明了怎么使用 MapGet 创建 HTTP Get 端点。
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
我们创建一个名为 Author 的 C# 文件,包含以下代码:
public class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
创建一个 Author 的只读列表,并填充一些数据,如下所示:
private readonly List<Author> _authors;
public Startup(IConfiguration configuration)
{
_authors = new List<Author>
{
new Author
{
Id = 1,
FirstName = "Joydip",
LastName = "Kanjilal"
},
new Author
{
Id = 2,
FirstName = "Steve",
LastName = "Smith"
},
new Author
{
Id = 3,
FirstName = "Julie",
LastName = "Lerman"
}
};
Configuration = configuration;
}
我们可以使用以下代码创建另一个端点,并以 JSON 格式返回作者列表。
endpoints.MapGet("/authors", async context =>
{
var authors = _authors == null ? new List<Author>() : _authors;
var response = JsonSerializer.Serialize(authors);
await context.Response.WriteAsync(response);
});
4. 在 ASP.NET Core 中使用轻量级服务检索记录
要根据 Id 检索特定记录,我们可以编写以下代码:
endpoints.MapGet("/authors/{id:int}", async context =>
{
var id = int.Parse((string)context.Request.RouteValues["id"]);
var author = _authors.Find(x=> x.Id == id);
var response = JsonSerializer.Serialize(author);
await context.Response.WriteAsync(response);
});
5. 在 ASP.NET Core 中使用轻量级服务创建记录
要使用 HTTP Post 添加数据,我们可以利用 MapPost 扩展方法,如下所示:
endpoints.MapPost("/", async context =>
{
var author = await context.Request.ReadFromJsonAsync<Author>();
_authors.Add(author);
var response = JsonSerializer.Serialize(author);
await context.Response.WriteAsync(response);
});
6. 在 ASP.NET Core 中使用轻量级服务删除记录
要删除数据,我们可以利用 MapDelete 扩展方法,如下所示:
endpoints.MapDelete("/authors/{id:int}", async context =>
{
var id = int.Parse((string)context.Request.RouteValues["id"]);
var author = _authors.Find(x => x.Id == id);
_authors.Remove(author);
var response = JsonSerializer.Serialize(_authors);
await context.Response.WriteAsync(response);
});
7. ASP.NET Core 中轻量级服务的配置方法
下面是 Startup 类的 Configure 方法的完整源码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
endpoints.MapGet("/authors", async context =>
{
var authors = _authors == null ? new List<Author>() : _authors;
var response = JsonSerializer.Serialize(authors);
await context.Response.WriteAsync(response);
});
endpoints.MapGet("/authors/{id:int}", async context =>
{
var id = int.Parse((string)context.Request.RouteValues["id"]);
var author = _authors.Find(x=> x.Id == id);
var response = JsonSerializer.Serialize(author);
await context.Response.WriteAsync(response);
});
endpoints.MapPost("/", async context =>
{
var author = await context.Request.ReadFromJsonAsync<Author>();
_authors.Add(author);
var response = JsonSerializer.Serialize(author);
await context.Response.WriteAsync(response);
});
endpoints.MapDelete("/authors/{id:int}", async context =>
{
var id = int.Parse((string)context.Request.RouteValues["id"]);
var author = _authors.Find(x => x.Id == id);
_authors.Remove(author);
var response = JsonSerializer.Serialize(_authors);
await context.Response.WriteAsync(response);
});
});
}
8. 在 ASP.NET Core 的 Program 类中创建轻量级服务
在 ASP.NET 6 中还有另一种创建轻量级服务的方法。我们创建新的 ASP.NET Core 6 空项目时,默认情况下不会创建 Startup.cs 文件。因此,我们可以在 Program.cs 文件中编写代码,创建轻量级服务。
下面的例子说明如何执行此操作:
app.MapGet("/", () => "Hello World!");
app.MapDelete("/{id}", (Func<int, bool>)((id) => {
// 删除记录代码
return true;
}));
app.MapPost("/", (Func<Author, bool>)((author) => {
// 添加记录代码
return true;
}));
app.Run();
轻量级服务或 API 没有模板,也不需要控制器类来创建它们。
我们可以在 Startup 或 Program 类中创建此类服务。
如果我们要在轻量级服务中实现授权,可以利用 IEndpointConventionBuilder 接口的 RequireAuthorization 扩展方法。
参考资料:
如何在 ASP.NET Core 中构建轻量级服务的更多相关文章
- 如何在ASP.NET Core 中快速构建PDF文档
比如我们需要ASP.NET Core 中需要通过PDF来进行某些简单的报表开发,随着这并不难,但还是会手忙脚乱的去搜索一些资料,那么恭喜您,这篇帖子会帮助到您,我们就不会再去浪费一些宝贵的时间. 在本 ...
- 如何在 ASP.Net Core 中使用 Lamar
ASP.Net Core 自带了一个极简的 开箱即用 的依赖注入容器,实际上,你还可以使用第三方的 依赖注入容器 来替代它,依赖注入是一种设计模式,它能够有效的实现对象之间的解耦并有利于提高单元测试和 ...
- [译]如何在ASP.NET Core中实现面向切面编程(AOP)
原文地址:ASPECT ORIENTED PROGRAMMING USING PROXIES IN ASP.NET CORE 原文作者:ZANID HAYTAM 译文地址:如何在ASP.NET Cor ...
- 如何在ASP.NET Core中实现CORS跨域
注:下载本文的完整代码示例请访问 > How to enable CORS(Cross-origin resource sharing) in ASP.NET Core 如何在ASP.NET C ...
- 如何在ASP.NET Core中实现一个基础的身份认证
注:本文提到的代码示例下载地址> How to achieve a basic authorization in ASP.NET Core 如何在ASP.NET Core中实现一个基础的身份认证 ...
- 如何在ASP.NET Core中应用Entity Framework
注:本文提到的代码示例下载地址> How to using Entity Framework DB first in ASP.NET Core 如何在ASP.NET Core中应用Entity ...
- [转]如何在ASP.NET Core中实现一个基础的身份认证
本文转自:http://www.cnblogs.com/onecodeonescript/p/6015512.html 注:本文提到的代码示例下载地址> How to achieve a bas ...
- 如何在ASP.NET Core中使用Azure Service Bus Queue
原文:USING AZURE SERVICE BUS QUEUES WITH ASP.NET CORE SERVICES 作者:damienbod 译文:如何在ASP.NET Core中使用Azure ...
- 如何在ASP.NET Core中自定义Azure Storage File Provider
文章标题:如何在ASP.NET Core中自定义Azure Storage File Provider 作者:Lamond Lu 地址:https://www.cnblogs.com/lwqlun/p ...
随机推荐
- hdu 1027 Ignatius and the Princess II(正、逆康托)
题意: 给N和M. 输出1,2,...,N的第M大全排列. 思路: 将M逆康托,求出a1,a2,...aN. 看代码. 代码: int const MAXM=10000; int fac[15]; i ...
- 测试开发【提测平台】分享13-远程搜索和路由$route使用实现新建提测需求
微信搜索[大奇测试开],关注这个坚持分享测试开发干货的家伙. 本篇继续提测平台开发,按惯例先给出学习的思维导图,以便快速了解学习知识和平台功能实现的重点. 基本知识点学习 远程搜索 显示的数据通过输入 ...
- 在Ubuntu下的C语言编程
以运行在虚拟机下的Ubuntu为例: mkdir fenchen 来创建一个文件夹 cd fenchen 切换到这个文件夹下面 vi test.c 创建并编辑一个test.c文件 按 i 编辑,之后把 ...
- no space left on device 磁盘空间不足
新挂载的目录,创建文件提示:no space left on device 1.执行命令:df -h ,查看盘是否挂载成功 2.用history命令查看历史命令,尴尬的发现挂载前忘记格式化了 3.取消 ...
- HashSet的remove方法(一道面试题)
1 public class CollectionTest { 2 3 @Test 4 public void test3(){ 5 HashSet set = new HashSet(); 6 Pe ...
- 文件与文件系统的压缩与打包 tar gzip bzip2
1:linux下常见的压缩文件后缀: .gz .zip .bz2 打包后的: .tar.gz .tar.zip .tar.bz2 2:gzip: 压缩:gzip file 解压:gunzip file ...
- k8s中部署springcloud
安装和配置数据存储仓库MySQL 1.MySQL简介 2.MySQL特点 3.安装和配置MySQL 4.在MySQL数据库导入数据 5.对MySQL数据库进行授权 1.MySQL简介 MySQL 是一 ...
- C++ STL的一些应用
STL一些应用 记录一些STL算法在开发中用得比较舒服的情况(不断添加...) lower_bound(begin,end,val)算法 算法说明 查找>=val的第一个元素,如果没有,返回en ...
- Flink 实践教程:入门(6):读取 PG 数据写入 ClickHouse
作者:腾讯云流计算 Oceanus 团队 流计算 Oceanus 简介 流计算 Oceanus 是大数据产品生态体系的实时化分析利器,是基于 Apache Flink 构建的具备一站开发.无缝连接.亚 ...
- 问题 A: 喷水装置(一)
题目描述 现有一块草坪,长为20米,宽为2米,要在横中心线上放置半径为Ri的喷水装置, 每个喷水装置的效果都会让以它为中心的半径为实数Ri(0<Ri<15)的圆被湿润,这有充足的喷水装置i ...