如何生成动态路径,响应在运行时生成的 swagger 中可能的参数值?

How to generate dynamic paths, resp possible parameter values in swagger that are generated at runtime?

我有一个带有 url 模板的 Web Api:'TestEmail/Render/{templateName}' 其中 templateName 参数的可能值是在运行时使用反射确定的。

public class TestEmailController : Controller
{
    public static IEnumerable<Type> AllNotificationTypes =>
       typeof(INotification).Assembly.GetTypes()
           .Where(t => typeof(INotification).IsAssignableFrom(t) && !t.IsAbstract);

    [HttpGet("[controller]/{templateName}")]
    public async Task<IActionResult> Render(string templateName)
    {
        Type templateType = AllNotificationTypes.FirstOrDefault(t => t.Name == templateName);
        if (templateType == null) return NotFound();
        string renderedHtml = ...
        return Content(renderedHtml, "text/html");
    }   
}

如何使用 Swashbuckle.AspNetCore 在 swagger 文件中反映可能的值?


编辑:受HelperSepu的回答启发,我得到了:

[SwaggerOperationFilter(typeof(TemplateNameOperationFilter))]
[HttpGet("[controller]/{templateName}")]
public async Task<IActionResult> Render(string templateName)
{ 
....


public class TemplateNameOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        var param = (PartialSchema)operation.Parameters.First(o => o.Name == "templateName");
        param.Enum = TestEmailController.AllNotificationTypes.Select(type => (object)type.Name).ToList();
    }
}

我在考虑这个,一个不错的选择是使用 IDocumentFilter

将 then 作为枚举
public class MyDocFilter : IDocumentFilter
{
  public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
  {
    PathItem path = swaggerDoc.Paths.Where(x => x.Key.Contains("TestEmail")).First().Value;
    var p = (NonBodyParameter)path.Get.Parameters.Where(x => x.Name == "templateName").First();
    p.Enum = new List<object>();
    foreach (var item in TestEmailController.AllNotificationTypes.Select(x => x.Name))
    {
      p.Enum.Add(item);
    }
  }
}

这将更改 UI 以显示下拉菜单: