我想在.NET7的最小API中为我的端点添加答案的示例.

我已经找到了几个有趣的资源,但它们都不能在最小的API环境中工作:

这些是我期望的渲染类型,即状态代码,及其描述和特定的端点(例如,假设我有针对不同情况的400个响应,我希望能够通过不同的描述和响应示例来区分它们).

例如,假设我有以下启动:

public class Startup
    {
        public IConfiguration Configuration
        {
            get;
        }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public void ConfigureServices(IServiceCollection services)
        {
            /* ... */
            // Swagger services
            services.AddEndpointsApiExplorer();
            services.AddSwaggerGen(BuilderUtils.SwaggerOptions());             
            /* ... */
        }
        public void Configure(WebApplication app)
        {
            // Swagger activation
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

        /* ... */



            app.MapMyEndpoints();

            app.Run();
        }
    }
}

使用以下方法:

public static void MapMyEndpoints(this WebApplication app)
{
    app.MapGet("/api/foo", () => return await Foo())
        .WithOpenApi(op => new(op)
        {
            OperationId = "MyOperationId",
            Tags = new List<OpenApiTag> { new() { Name = "MyTag" } },
            Summary = "MySummary",
            Description = "MyDescription"
        });

    app.MapGet("/api/bar", () => return await Bar())
        .WithOpenApi(op => new(op)
        {
            OperationId = "MyOperationId",
            Tags = new List<OpenApiTag> { new() { Name = "MyTag" } },
            Summary = "MySummary",
            Description = "MyDescription"
        });
}

两者都将使用MessageBody类进行响应:

public class MessageBody
{
    public string? Message { get; set; }
        public string? Error { get; set; }
}

例如,foo将使用MessageBody: Message="已连接",

或使用MessageBody的400: 错误="密码错误" 或错误="找不到帐户"

其他终端也是如此.

我想在我的Swagger里报告所有这些情况.

因为我使用最少的API工作,所以我不能使用示例过滤器,或者如果我可以,我不知道如何使用.

如果有人对我如何做到这一点有任何提示,我将不胜感激!

推荐答案

安装Swashbuckle.AspNetCore.Filters Nuget,然后您可以使用相应的属性来标记处理程序:

builder.Services.AddSwaggerGen(options => options.ExampleFilters());
builder.Services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());

// ...

app.MapGet("/api/bar",
        [SwaggerResponseExample((int)HttpStatusCode.OK, typeof(MessageBodyOkExample))]
        [SwaggerResponseExample((int)HttpStatusCode.BadRequest, typeof(MessageBody400Example))]
        () => new MessageBody
        {
            Message = "Connected"
        })
    .WithOpenApi(op => new(op)
    {
        // ...
    })
    .Produces<MessageBody>((int)HttpStatusCode.OK)
    .Produces<MessageBody>((int)HttpStatusCode.BadRequest);

和样本回复:

public class MessageBodyOkExample : IExamplesProvider<MessageBody>
{
    public MessageBody GetExamples()
    {
        return new MessageBody()
        {
            Message = "Connected"
        };
    }
}

public class MessageBody400Example : IExamplesProvider<MessageBody>
{
    public MessageBody GetExamples()
    {
        return new MessageBody()
        {
            Error = "testError"
        };
    }
}

结果是:

enter image description here

Csharp相关问答推荐

如何设置和接收自定义Visual Studio项目命令的参数

C#如何克服getter的接口空性

Blazor:子编辑表单上的嵌套编辑表单验证

PostingAsJsonAschange在从调用的方法返回时给出500错误

使用其可能实现的基类和接口的属性的方法

如何使用Unity和MRTK3将手网添加到Hololens 2应用程序中

从应用程序图API调用访问所有者字段

从.Net 6 DLL注册和检索COM对象(Typelib导出:类型库未注册.(异常来自HRESULT:0x80131165))

Azure函数中实体框架核心的依赖注入

HttpClient 415不支持的媒体类型错误

将类移动到新命名空间后更新RavenDB Raven-Clr-Type

DbContext-传递自定义配置选项

C#自定义验证属性未触发IsValid方法

C# Winforms:从对象树到TreeView的递归转换重复条目

如何对特定异常使用Polly重试机制?

从MudAutoComplete打开对话框,列表仍然可见

在C#/ASP.NET Core 7中,什么可能导致POST请求作为GET请求发送

使用LibraryImport在多个dll中导入相同的函数

反序列化我以前使用System.Text.Json序列化的文件时出现异常

如何使ExecuteAsync异步运行