Swashbuckle 重命名模型中的数据类型 [英] Swashbuckle rename Data Type in Model

查看:31
本文介绍了Swashbuckle 重命名模型中的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在组合一个需要匹配外部源 XML 格式的 Web API,并希望在 swagger 输出中重命名数据类型对象.

I'm putting together a web API that needs to match an external sources XML format and was looking to rename the Data Type objects in the swagger output.

它在类成员上运行良好,但我想知道是否也可以覆盖类名.

It's working fine on the members of the class but I was wondering if it was possible to override the class name as well.

例子:

[DataContract(Name="OVERRIDECLASSNAME")]
public class TestItem
{
   [DataMember(Name="OVERRIDETHIS")]
   public string toOverride {get; set;}
}

在生成的输出中,我最终看到型号:

In the generated output I end up seeing Model:

   TestItem {
      OVERRIDETHIS (string, optional)
   }

我希望看到

覆盖类名 {OVERRIDETHIS(字符串,可选)}

OVERRIDECLASSNAME { OVERRIDETHIS (string, optional) }

这可能吗?

谢谢,

推荐答案

我有同样的问题,我想我现在解决了.

I had the same problem and I think I solved it now.

首先在 Swagger 配置中添加 SchemaId(从版本 5.2.2 见 https://github.com/domaindrivendev/Swashbuckle/issues/457):

First of all add SchemaId in Swagger Configuration (from version 5.2.2 see https://github.com/domaindrivendev/Swashbuckle/issues/457):

GlobalConfiguration.Configuration
    .EnableSwagger(c =>
    {
        c.SchemaId(schemaIdStrategy);
        [...]
    }

然后添加这个方法:

private static string schemaIdStrategy(Type currentClass)
{
    string returnedValue = currentClass.Name;
    foreach (var customAttributeData in currentClass.CustomAttributes)
    {
        if (customAttributeData.AttributeType.Name.ToLower() == "datacontractattribute")
        {
            foreach (var argument in customAttributeData.NamedArguments)
            {
                if (argument.MemberName.ToLower() == "name")
                {
                    returnedValue = argument.TypedValue.Value.ToString();
                }
            }
        }
    }
    return returnedValue;
}

希望对你有帮助.

这篇关于Swashbuckle 重命名模型中的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆