如何在ASP.NET最小API中的Swagger中添加示例响应?

huangapple go评论76阅读模式
英文:

How to add example responses in Swagger in a ASP .NET minimal API?

问题

I would like to add examples of answers for my endpoints in my minimal API in .NET 7.

我想为我的.NET 7中的最小API添加端点响应示例。

I have already found several interesting resources but none of them work in the context of a minimal API:

我已经找到了一些有趣的资源,但它们都不适用于最小API的情境:

These are the kind of renderings I expect, i.e. a status code, with its description and a specific endpoint (e.g. suppose I have several 400 responses for different cases, I want to be able to differentiate them with a different description and response example).

这是我期望的渲染方式,即状态代码,带有其描述和特定端点(例如,假设我有多个不同情况的400响应,我希望能够使用不同的描述和响应示例来区分它们)。

For example, let imagine that I have the following Startup :

例如,让我们想象我有以下的Startup:

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();
    }
}

With the following method:

使用以下方法:

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"
        });
}

Both will respond using the MessageBody class:

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

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

For example, Foo will respond either a 200 with the MessageBody:
Message = "Connected",

例如,Foo将使用MessageBody响应200,其中:
Message = "Connected",

or 400 with the MessageBody:
Error = "Wrong Password"
or Error = "Account not found"

或者400响应将使用MessageBody:
Error = "Wrong Password"
或Error = "Account not found"

And it goes on for the other endpoints.

对于其他端点也是如此。

I want to report all of those cases in my Swagger.

我想在我的Swagger中报告所有这些情况。

Because I work using minimal API, I can't use Exemple Filters, or if I can, I don't know how.

因为我使用最小API工作,我不能使用Exemple Filters,或者如果可以的话,我不知道如何使用。

If anyone have a hints on how I can do that I will be really gratefull !

如果有人有关于如何做到这一点的提示,我将非常感激!

英文:

I would like to add examples of answers for my endpoints in my minimal API in .NET 7.

I have already found several interesting resources but none of them work in the context of a minimal API:

These are the kind of renderings I expect, i.e. a status code, with its description and a specific endpoint (e.g. suppose I have several 400 responses for different cases, I want to be able to differentiate them with a different description and response example).

For example, let imagine that I have the following Startup :

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

	    /* ... */



            app.MapMyEndpoints();

            app.Run();
        }
    }
}

With the following method:

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

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

Both will respond using the MessageBody class :

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

For example, Foo will respond either a 200 with the MessageBody :
Message = "Connected",

or 400 with the MessageBody :
Error = "Wrong Password"
or Error = "Account not found"

And it goes on for the other endpoints.

I want to report all of those cases in my Swagger.

Because I work using minimal API, I can't use Exemple Filters, or if I can, I don't know how.

If anyone have a hints on how I can do that I will be really gratefull !

答案1

得分: 2

安装 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"
        };
    }
}

和结果:

如何在ASP.NET最小API中的Swagger中添加示例响应?

英文:

Install the Swashbuckle.AspNetCore.Filters nuget and then you can mark handlers with corresponding attributes:

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

// ...

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

And sample responses:

public class MessageBodyOkExample : IExamplesProvider&lt;MessageBody&gt;
{
    public MessageBody GetExamples()
    {
        return new MessageBody()
        {
            Message = &quot;Connected&quot;
        };
    }
}

public class MessageBody400Example : IExamplesProvider&lt;MessageBody&gt;
{
    public MessageBody GetExamples()
    {
        return new MessageBody()
        {
            Error = &quot;testError&quot;
        };
    }
}

And result:

如何在ASP.NET最小API中的Swagger中添加示例响应?

huangapple
  • 本文由 发表于 2023年5月17日 20:50:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定