WTM icon indicating copy to clipboard operation
WTM copied to clipboard

【特性】公共函数不应在swagger文档里面显示锁的图标

Open fawdlstty opened this issue 4 years ago • 3 comments

修复方式:ConfigureServices函数里添加c.OperationFilter<SecurityRequirementsOperationFilter> (); 我个人实现方式:

using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using QingjiuServer3.Auth;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;

namespace QingjiuServer3 {
    public class SecurityRequirementsOperationFilter: IOperationFilter {
        public void Apply (OpenApiOperation operation, OperationFilterContext context) {
            if (operation == null || context == null)
                return;
            var requiredScopes = context.MethodInfo.GetCustomAttributes (true).OfType<MyAuthAttribute> ().Select (attr => attr.Policy).Distinct ();

            if (requiredScopes.Any ()) {
                operation.Responses.Add ("401", new OpenApiResponse { Description = "Unauthorized" });
                operation.Responses.Add ("403", new OpenApiResponse { Description = "Forbidden" });
                operation.Description = $"{requiredScopes.First ()}<br />{operation.Description}";
                operation.Security = new List<OpenApiSecurityRequirement> {
                    new OpenApiSecurityRequirement {
                        [new OpenApiSecurityScheme {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                        }] = requiredScopes.ToList ()
                    }
                };
            }
        }
    }
}

然后如果没有标记MyAuth就不会显示锁的图标;标记后就会显示锁的图标。 我的MyAuthAttribute的Policy是为了给函数加上说明,比如【此函数只有管理员可访问】等,这个字符串将拼接在所有用户自定义的函数说明之前。这样做的好处是,用户不需要对所有函数的可访问性专门做一个描述。示例:用户描述是:此函数用于登录,Policy自动生成的字符串是【此函数无需验证,任何人均可调用】,那么最终文档效果是:

【此函数无需验证,任何人均可调用】
此函数用于登录

fawdlstty avatar Mar 12 '20 07:03 fawdlstty

此功能配合pr #325 中的“启用文档注释”功能,可以使得效果最佳

fawdlstty avatar Mar 12 '20 07:03 fawdlstty

image 另外还有一个这样的问题:使用enum做controller接收的参数,swagger里显示不友好

fawdlstty avatar Mar 12 '20 08:03 fawdlstty

再提一个建议,去掉[ActionDescription],改为读注释

fawdlstty avatar Mar 13 '20 08:03 fawdlstty