Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swashbuckle rename Data Type in Model

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.

Example:

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

I'd hope to see

OVERRIDECLASSNAME { OVERRIDETHIS (string, optional) }

Is this possible?

Thanks,

like image 949
weretaco Avatar asked Aug 13 '15 23:08

weretaco


2 Answers

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.

like image 84
Luca Natali Avatar answered Sep 18 '22 05:09

Luca Natali


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;
    }
like image 39
Yiorgos Avatar answered Sep 19 '22 05:09

Yiorgos