Skip to content

Instantly share code, notes, and snippets.

@RobThree
Created September 21, 2018 16:36
Show Gist options
  • Save RobThree/911814b4499aaeaebd9066ed69713884 to your computer and use it in GitHub Desktop.
Save RobThree/911814b4499aaeaebd9066ed69713884 to your computer and use it in GitHub Desktop.
Swashbuckle.AspNetCore DocumentOperationRoleRequirementsFilter
using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
using System.Reflection;
using System.Web;
namespace MyNameSpace {
public class DocumentOperationRoleRequirementsFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
// Get AuthorizeAttribute Roles
var roles = context.MethodInfo.GetCustomAttributes<AuthorizeAttribute>().Select(a => a.Roles).FirstOrDefault();
if (!string.IsNullOrEmpty(roles))
{
operation.Description = $@"**Roles Required:** {string.Join(", ", roles.Split(',').Select(r => $"<code>{HttpUtility.HtmlEncode(r)}</code>"))}<br/>{operation.Description}";
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment