【问题标题】:How to implement a Swashbuckle IOperationFilter that processes custom attributes in .NET Core如何在 .NET Core 中实现处理自定义属性的 Swashbuckle IOperationFilter
【发布时间】:2020-03-01 08:28:16
【问题描述】:

我已经实现了Swashbuckle.Swagger.IOperationFilter 来处理自定义属性,如下所述:https://stackoverflow.com/a/52948376/13087

我现在想为Swashbuckle.AspNetCore 5.0.0 做类似的事情。

似乎ApiDescription 类没有在原始实现中使用的扩展方法GetControllerAndActionAttributes。我尝试通过查看它的 source code 来重新实现它,但它使用了我在 .NET Core 中似乎不存在的成员 ApiDescription.ActionDescriptor.ControllerDescriptorApiDescription.ActionDescriptor.GetCustomAttributes<TAttribute>

谁能帮助我开始向我展示如何从 IOperationFilter 获取自定义控制器和操作属性?

更新 看起来 .NET Framework 实现有一个 ActionDescriptor,实际上是一个 ReflectedActionDescriptor。这个类有一个构造函数,它接受一个MethodInfo,用于查找属性。

但我看不到任何方法可以为 .NET Core 实现 Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor 获取 MethodInfo

【问题讨论】:

    标签: asp.net-core asp.net-core-2.1 swashbuckle swashbuckle.aspnetcore


    【解决方案1】:

    我找到了答案:有一个扩展方法 ApiDescription.TryGetMethodInfo 将获得 MethodInfo 并因此可以访问自定义属性。

    【讨论】:

      【解决方案2】:

      使用这样的代码:

      var attributes = apiDescription.GetControllerAndActionAttributes<AuthorizeAttribute>();
      if (!attributes.IsNullOrEmpty())
      {
          var param = new Parameter
          {
              name = "Authorization",
              @in = "header",
              description = "Bearer + access token",
              required = false,
              type = "string"
          };
      
          if (operation.parameters == null)
              operation.parameters = new List<Parameter> { param };
          else
              operation.parameters.Add(param);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-22
        • 2019-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-01
        相关资源
        最近更新 更多