关于c#:如何在-ASPNET-Core-中构建轻量级服务

6次阅读

共计 5220 个字符,预计需要花费 14 分钟才能阅读完成。

在 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 接口的一些扩大办法来映射申请。

以下是这些扩大办法的列表:

  1. MapGet
  2. MapPost
  3. MapDelete
  4. MapPut
  5. MapRazorPages
  6. MapControllers
  7. MapHub
  8. 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 扩大办法。

参考资料:

  • 编程宝库
  • C# 编程
正文完
 0