Asp.Net core Swashbuckle 设置 operationId [英] Asp.Net core Swashbuckle set operationId

查看:13
本文介绍了Asp.Net core Swashbuckle 设置 operationId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Asp.Net Core 2.1 项目中设置 swagger operationId 属性?根据 this 帖子我应该使用 SwaggerOperationAttribute 但我在 Swashbuckle.AspNetCore 库中找不到它.还有一个 IOOperationFilter

How can I set swagger operationId attribute in Asp.Net Core 2.1 project? According to this post I should use SwaggerOperationAttribute but I cannot find it in Swashbuckle.AspNetCore library. Also there is an IOperationFilter

public interface IOperationFilter
{
    void Apply(Operation operation, OperationFilterContext context);
}

而且我找不到任何用于大摇大摆的实现.

and I can't find any implementations for swagger generation purposes.

推荐答案

还有 2 个其他选项,无需编写任何额外的代码或添加额外的依赖项,如 Swashbuckle.AspNetCore.Annotations

There are 2 other options without having to write any extra code or add extra dependency like Swashbuckle.AspNetCore.Annotations

选项 1:基于约定 - SwaggerGen 具有设置 CustomOperationIds 的选项.因此,您可以像这样简单地将其设置为使用 ControllerName_HttpMethod:

Option 1: Convention based - SwaggerGen has an option to set CustomOperationIds. So you can simply set it to use ControllerName_HttpMethod like this:

services.AddSwaggerGen(c =>
{
    c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{e.HttpMethod}");
    c.SwaggerDoc("v1", new Info { Title = "Test API", Version = "v1" });
});

这将按照 ControllerName_HttpMethod 约定将 operationIds 添加到您的所有方法中.

This will add operationIds to all your methods, following ControllerName_HttpMethod convention.

选项 2:基于 ActionFilter/Attribute - 您可以配置每个 Action 方法(就像使用 SwaggerOperation 操作过滤器一样,只需添加一个 Name 属性添加到您的 HTTP 动词操作过滤器,如下所示:

Option 2: ActionFilter/Attribute based - you can configure each Action method (as you'd do with SwaggerOperation action filter by simple adding a Name property to your HTTP verb action filter like this:

[HttpPost(Name="Post_Person")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Response>> PostAsync([FromBody]Request request)
{
    Response result = await _context.PostAsync(request);
    return Ok(result);
}

这与 [SwaggerOperation(OperationId = "Post_Person")] 完全一样,但不需要 EnableAnnotations

This works exactly like [SwaggerOperation(OperationId = "Post_Person")] but without the need of EnableAnnotations

这篇关于Asp.Net core Swashbuckle 设置 operationId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆