master
bicijinlian 4 years ago
parent c3929e516b
commit b682f89c8a

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
@ -29,6 +30,7 @@ namespace SwaggerStudy.Controllers
_studentServer = studentServer;
}
[AllowAnonymous]
[HttpGet]
public ResultBase GetAll()
{
@ -67,6 +69,7 @@ namespace SwaggerStudy.Controllers
/// </example>
/// <remarks>我是Remark注释</remarks>
/// <param name="studentId" example="1">学生Id(变量在路由中时example才有用)</param>
[AllowAnonymous]
[HttpGet("{studentId:int}")]
public IActionResult Get([FromRoute]int studentId)
{
@ -80,6 +83,7 @@ namespace SwaggerStudy.Controllers
return Ok(apiResult);
}
[AllowAnonymous]
[HttpGet]
[ActionName("GetAsync")]
public async Task<IActionResult> GetAsync(int studentId)

@ -836,7 +836,7 @@ services.AddSwaggerGen(c =>
};
```
_NOTE: Filter pipelines are DI-aware. That is, you can create filters with constructor parameters and if the parameter types are registered with the DI framework, they'll be automatically injected when the filters are instantiated_
_注意: 过滤器管道可识别。也就是说您可以使用构造函数参数创建过滤器如果参数类型注册到DI框架中那么当过滤器被实例化时它们将被自动注入_
#### Schema 筛选器 ####

@ -0,0 +1,32 @@
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 = "" });
}
}
}
}

@ -92,6 +92,10 @@ namespace SwaggerStudy
return i;
});
#region 过滤器
setup.OperationFilter<AuthResponsesOperationFilter>();
#endregion
});
//配置SwaggerGen

Loading…
Cancel
Save