0

I have an api app where the controller method takes a class as input. I'm using Swagger to show the user what variables are in that class. I used the class for other purposes so for certain methods I'd like Swagger not to show certain objects. I tried the attribute [IgnoreDataMember] mentioned here, but it didn't seem to do anything. How can I prevent Swagger from showing every object in the input class?

So here is the method definition:

[HttpPost("Receive")]
[Produces("application/json", Type = typeof(APIResponse))]
public APIResponse Receive(MyClass item)
{....}

MyClass is defined with 4 objects:

public class MyClass
{
    [IgnoreDataMember]
    public int itemID { get; set; }
    [IgnoreDataMember]
    public int quantity { get; set; }
    public int vendor_id { get; set; }
    public string ship_name { get; set; }
}

Right now, Swagger shows all 4 objects as parameters:

enter image description here

For this method, I'd like to only show 2 of the 4 class objects as parameters. For other methods, I'll need to show all 4. Is there a way to do this or will I need to create a class for each method?

boilers222
  • 1,901
  • 7
  • 33
  • 71
  • Maybe related https://stackoverflow.com/questions/41005730/how-to-configure-swashbuckle-to-ignore-property-on-model/46237000 – Hackerman Jun 13 '18 at 21:20

1 Answers1

1

By default, Swagger is not prepared to do that, in case you want to have a parameter, you can add a default value like

public void myMethod(string a = "abc", int a = 1)

But, if you want to omit completely a parameter, you can do a hack like this:

Add a new file with the name CustomSchemaFilters

public class CustomSchemaFilters : ISchemaFilter
{
    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
        var excludeProperties = new[] {"name", "lastname, "token"};

        foreach(var prop in excludeProperties)
            if (schema.properties.ContainsKey(prop))
                schema.properties.Remove(prop);
    }
}

and in your file AppStart/SwaggerConfig.cs

And add in the same file, this line

c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

just inside of:

GlobalConfiguration.Configuration .EnableSwagger(c => { ...

Add the line:

c.SchemaFilter<CustomSchemaFilters>();

Benjamin RD
  • 11,516
  • 14
  • 87
  • 157
  • Thanks! Seems like it would be much easier just to add a second class, which I can do in this case. I'm going to keep your code because I could see in the future having a class I can't change where I would have to use this. – boilers222 Jun 14 '18 at 11:58