将 AllowAnonymousAttribute 与 Swashbuckle 一起使用

Using AllowAnonymousAttribute with Swashbuckle

我正在尝试将 Swagger(通过 Swashbuckle 5.6.0)添加到 .Net 4.5.1 WebAPI

在我 运行 通过以下 AdminController.cs 中的新 ActionFilterAttribute 属性通过自定义授权过滤器之前,我能够让事情正常进行:

public class AdminController : BaseApiController
{
    [CustomAuthorize( )]
    [HttpGet]
    public GenericResponse ClearCache()
    {
        using (var businessAccess = IoCContainer.Resolve<IAdminBusinessAccess>())
        {
            var response = new GenericResponse();

            businessAccess.ClearCache();

            return response;
        }
    }
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CustomAuthorizeAttribute : ActionFilterAttribute
{
    public Enumerations.SecurityCheck SecurityCheck { get; set; }
}

现在,我的 Swagger UI 停止获取资源,直到 Chrome 崩溃。如果我注释掉这个 ActionFilterAttribute 属性,一切正常。有谁知道如何使用带有授权属性的 Swashbuckle 或 Swagger?

我使用授权而不需要 ActionFilterAttribute 像这样:

public class KeyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        IEnumerable<string> apiKey;
        if (actionContext.Request.Headers.TryGetValues("apiKey", out apiKey))
        {
            return apiKey.First() == "123"; 
        }
        return false;
    }
}

https://github.com/heldersepu/nhc-noaa/blob/master/nhc-noaa/App_Start/KeyAuthorizeAttribute.cs

然后是动作:

    [KeyAuthorize]
    public Test PostEcho([FromBody] List<Test> tests)
    {
        return tests.FirstOrDefault();
    }

最后在你的 swagger.config

c.ApiKey("apiKey", "header", "API Key Authentication", typeof(KeyAuthorizeAttribute));

您应该会在 UI:
上得到一个不错的授权框 https://nhc-noaa.azurewebsites.net/swagger/ui/index

ActionFilterAttribute 对您来说是一个硬性要求吗?