Swashbuckle rename Data Type in Model

我是研究僧i 提交于 2019-12-06 02:57:37

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

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);
        [...]
    }

Then add this method:

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

Hope it helps.

Pretty old question, but as I was looking for a similar solution, I bumped into this. I think the code in Vincent's answer might not work. Here is my take on it:

    private static string schemaIdStrategy(Type currentClass)
    {
        var dataContractAttribute = currentClass.GetCustomAttribute<DataContractAttribute>();
        return dataContractAttribute != null && dataContractAttribute.Name != null ? dataContractAttribute.Name : currentClass.Name;
    }

Adding to the thread as I am not able to use the answer with Swashbukle for AspNetCore. I am doing this. However I am not totally happy as if the object is contain in another object it is showing its original name. For example if you have a result set that is Paged That result is shown incorrectly.So this is not a final answer but might work on simple use cases.

I am using a Schema Filter. And the object just have [JsonObject(Title="CustomName")] as I get the Title property for the data type. First Define a class like this:

public class CustomNameSchema : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaFilterContext context)
        {
            if (schema?.Properties == null)
            {
                return;
            }

            var objAttribute = context.SystemType.GetCustomAttribute<JsonObjectAttribute>();
            if( objAttribute!= default && objAttribute?.Title?.Length > 0)
            {
                schema.Title = objAttribute.Title;
            }
        }
    }

On the startup you must configure a SchemaFilter

c.SchemaFilter<CustomNameSchema>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!