在ASP.NET Core Web API中使用Swashbuckle 6(Swagger)重命名模型

17

我正在使用ASP.NET Core Web API的Swashbuckle 6(Swagger)。我的模型有DTO作为后缀,例如:

public class TestDTO {
    public int Code { get; set; }
    public string Message { get; set; }
}

我该如何在生成的文档中将其重命名为"Test"?我尝试添加一个带有名称的DataContract属性,但没有帮助。

[HttpGet]
public IActionResult Get() {
  //... create List<TestDTO>
  return Ok(list);
}
3个回答

41

搞定了...类似于这里的答案: Swashbuckle 重命名模型中的数据类型

唯一的区别是属性现在叫做 CustomSchemaIds 而不是 SchemaId:

options.CustomSchemaIds(schemaIdStrategy);

我不研究DataContract属性,只是将“DTO”移除:

private static string schemaIdStrategy(Type currentClass) {
    string returnedValue = currentClass.Name;
    if (returnedValue.EndsWith("DTO"))
        returnedValue = returnedValue.Replace("DTO", string.Empty);
    return returnedValue;
}

这是一个非常有帮助的答案。 - Michi-2142
5
一个快速的内联解决方案可能是:c.CustomSchemaIds(type => type.Name.EndsWith("DTO") ? type.Name.Replace("DTO", string.Empty) : type.Name); (说明:此代码片段是C#语言的Lambda表达式,用于根据特定条件设置自定义模式ID。翻译尽力保留原文意思并简化句子,如有歧义,请参考原文。) - Pavlos
给了我一些想法,可以从EFCore生成的类中删除“tbl”。谢谢@ultravelocity! - Rob Koch

2

@ultravelocity的答案对我来说并不完全有效。错误信息是“'Response`1'已经被使用”。我不知道确切的原因,但我猜测可能与继承/泛型有关(因为我返回了分页响应)。

基于@ultravelocity的问题和答案,我为.net 5开发了一个可能的解决方案(也许适用于asp.net core 2.c/3.d),以解决这个问题。

步骤:

  1. 添加类似@ultravelocity的customSchemaId-Strategy
a.CustomSchemaIds(schemaIdStrategy);
  1. 添加自定义策略函数
private static string schemaIdStrategy(Type currentClass)
{
    string customSuffix = "Response";
    var tmpDisplayName = currentClass.ShortDisplayName().Replace("<", "").Replace(">", "");
    var removedSuffix = tmpDisplayName.EndsWith(customSuffix) ? tmpDisplayName.Substring(0, tmpDisplayName.Length - customSuffix.Length) : tmpDisplayName;
    return removedSuffix;
}

在被接受的答案中,泛型显然存在问题。此外,ShortDisplayName是从哪里来的? - Neistow

0
如果有人对仅仅更改默认模式标识感兴趣,他们可以使用这个实现:
private static string DefaultSchemaIdSelector(Type modelType)
{
    if (!modelType.IsConstructedGenericType) return modelType.Name.Replace("[]", "Array");

    var prefix = modelType.GetGenericArguments()
        .Select(genericArg => DefaultSchemaIdSelector(genericArg))
        .Aggregate((previous, current) => previous + current);

    return prefix + modelType.Name.Split('`').First();
}

然后继续像这样建立起来
options.CustomSchemaIds(type => DefaultSchemaIdSelector(type).Replace("DTO", string.Empty));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接