如何使用 OpenAPI 和 Scalar API 文档对控制器进行分组

问题描述 投票:0回答:1

我有一个 ASP.NET Core 9 Web API 应用程序。默认情况下,.NET9 不再使用 Swashbuckle。为了生成 API 文档,我使用 Microsoft OpenAPI 文档Scalar

效果很好。我需要将所有端点分组为更小的组。例如,用户,订单等。用户组将包含身份验证控制器,更改配置文件控制器,订单组将包含订单控制器和支付控制器。

是否可以对这些端点进行分组?

c# asp.net-core-webapi openapi swashbuckle .net-9.0
1个回答
0
投票

您可以同时使用

Swashbuckle.AspNetCore
Scalar.AspNetCore
对控制器和端点进行分组。

您可以查看以下示例:

NET9API.csproj:从 NuGet 安装了

Swashbuckle.AspNetCore
Scalar.AspNetCore
包。

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.0" />
    <PackageReference Include="Scalar.AspNetCore" Version="1.2.44" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.9.0" />
  </ItemGroup>

</Project>

然后,在Program.cs文件中:

using Scalar.AspNetCore;
using NET9API.Controllers;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();
}

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
};

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.MapUserEndpoints(); //after adding the "API endpoints via API with Read/write endpoints" Scaffold, we can add the maps.
  
app.Run();

然后,我们可以使用以下选项来添加控制器或端点:

add controller

在此示例中,我以与上述相同的方式添加了值控制器和用户端点。

ValuesController.cs 文件如下:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET: api/<ValuesController>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<ValuesController>/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<ValuesController>
    [HttpPost]
    public void Post([FromBody] string value)
    {
    }

    // PUT api/<ValuesController>/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody] string value)
    {
    }

    // DELETE api/<ValuesController>/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

以及UsersController.cs文件如下:

using NET9API.Models;
namespace NET9API.Controllers;

public static class UsersController
{
    public static void MapUserEndpoints (this IEndpointRouteBuilder routes)
    {
        var group = routes.MapGroup("/api/User").WithTags(nameof(User));

        group.MapGet("/", () =>
        {
            return new [] { new User() };
        })
        .WithName("GetAllUsers")
        .WithOpenApi();

        group.MapGet("/{id}", (int id) =>
        {
            //return new User { ID = id };
        })
        .WithName("GetUserById")
        .WithOpenApi();

        group.MapPut("/{id}", (int id, User input) =>
        {
            return TypedResults.NoContent();
        })
        .WithName("UpdateUser")
        .WithOpenApi();

        group.MapPost("/", (User model) =>
        {
            //return TypedResults.Created($"/api/Users/{model.ID}", model);
        })
        .WithName("CreateUser")
        .WithOpenApi();

        group.MapDelete("/{id}", (int id) =>
        {
            //return TypedResults.Ok(new User { ID = id });
        })
        .WithName("DeleteUser")
        .WithOpenApi();
    }
}

运行应用程序后,使用Scalar检查openAPI json文件(

https://localhost:{port}/openapi/v1.json
),输出如下:

test result

© www.soinside.com 2019 - 2024. All rights reserved.