dotnetcore / dotnetcore/WTM

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

Open
#330 3 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
C#
Stars
4.3k
Forks
896
PR merge metrics
No merged PRs in 30d

Description

修复方式:ConfigureServices函数里添加`c.OperationFilter ();`
我个人实现方式:
```csharp
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 ().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 ()}
{operation.Description}";
operation.Security = new List {
new OpenApiSecurityRequirement {
[new OpenApiSecurityScheme {
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
}] = requiredScopes.ToList ()
}
};
}
}
}
}
```
然后如果没有标记MyAuth就不会显示锁的图标;标记后就会显示锁的图标。
我的MyAuthAttribute的Policy是为了给函数加上说明,比如【此函数只有管理员可访问】等,这个字符串将拼接在所有用户自定义的函数说明之前。这样做的好处是,用户不需要对所有函数的可访问性专门做一个描述。示例:用户描述是:`此函数用于登录`,Policy自动生成的字符串是`【此函数无需验证,任何人均可调用】`,那么最终文档效果是:
```
【此函数无需验证,任何人均可调用】
此函数用于登录
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.