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

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

问题描述

我正在整理一个Web API,该API需要匹配外部源XML格式,并希望在swagger输出中重命名Data Type对象.

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)
   }

我希望看到

OVERRIDECLASSNAME {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天全站免登陆