Asp.Net core Swashbuckle set operationId

前端 未结 3 1951
梦谈多话
梦谈多话 2021-01-02 15:59

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

3条回答
  •  醉梦人生
    2021-01-02 16:54

    Finally, I came to this solution:

    public class SwaggerOperationNameFilter : IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {
            operation.OperationId = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
                .Union(context.MethodInfo.GetCustomAttributes(true))
                .OfType()
                .Select(a => a.OperationId)
                .FirstOrDefault();
        }
    }
    
    [AttributeUsage(AttributeTargets.Method)]
    public sealed class SwaggerOperationAttribute : Attribute
    {
        public SwaggerOperationAttribute(string operationId)
        {
            OperationId = operationId;
        }
    
        public string OperationId { get; }
    }
    
    // Startup.cs
    services.AddSwaggerGen(c =>
    {
        ...
        c.OperationFilter();
    };
    
    [HttpGet("{id:int}")]
    [SwaggerOperation("GetById")]
    public async Task Get(int id)
    {
        ...
    }
    

    But it still seems to me that I've reinvented the wheel.

提交回复
热议问题