You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
1.2 KiB
C#
33 lines
1.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.OpenApi.Models;
|
|
using Swashbuckle.AspNetCore.Swagger;
|
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
|
using Swashbuckle.AspNetCore.SwaggerUI;
|
|
|
|
namespace SwaggerStudy
|
|
{
|
|
/// <summary>
|
|
/// Swagger Operation过滤器
|
|
/// 列出了用AuthorizeAttribute修饰的所有操作附加"401"响应
|
|
/// </summary>
|
|
public class AuthResponsesOperationFilter : IOperationFilter
|
|
{
|
|
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
|
{
|
|
var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
|
|
.Union(context.MethodInfo.GetCustomAttributes(true));
|
|
var cc = authAttributes .OfType<AuthorizeAttribute>();
|
|
|
|
if (authAttributes .OfType<AuthorizeAttribute>().Any() || authAttributes .OfType<AllowAnonymousAttribute>().Any())
|
|
{
|
|
operation.Responses.Add("401", new OpenApiResponse { Description = "未授权" });
|
|
operation.Responses.Add("403", new OpenApiResponse { Description = "" });
|
|
}
|
|
}
|
|
}
|
|
}
|