首页 > 编程技术 > csharp

使用VS2022在ASP.NET Core中构建轻量级服务

发布时间:2021-12-8 12:58 作者:编程宝库

在 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 项目。

这将在 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 用于 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 扩展方法。

参考资料:

​编程宝库​​​

​C#编程​

以上所述是小编给大家介绍的使用VS2022在ASP.NET Core中构建轻量级服务,希望对大家有所帮助。在此也非常感谢大家对猪先飞网站的支持!

原文出处:https://www.cnblogs.com/wanghao72214/p/15659718.html

标签:[!--infotagslink--]

您可能感兴趣的文章: