Reputation: 101
In my API the entity has some fields which are inherited from related objects.
Therefore in POST
method I don't want them to be visible in model schema in swagger-UI but I would like them to be displayed in the response. Is that possible?
At this moment, as a workaround I use [ReadOnly(true)]
attribute on the DTO's fields but it's not a perfect solution.
Upvotes: 1
Views: 1160
Reputation: 101
I eventually resolved this by using 2 different DTOs:
On controller level the InputDTO is used as method argument, the ResponseDTO is declared in attribute [ResponseType(typeof(ResponseDTO))].
Hope this helps others!
Upvotes: 0
Reputation: 3778
try with this:
Create a class like:
[AttributeUsage(AttributeTargets.Property)]
public class SwaggerExcludeAttribute : Attribute
{
}
public class SwaggerExcludeFilter : Attribute, ISchemaFilter
{
#region ISchemaFilter Members
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
if (schema?.properties == null || type == null)
return;
var excludedProperties = type.GetProperties()
.Where(t =>
t.GetCustomAttribute<SwaggerExcludeAttribute>()
!= null);
foreach (var excludedProperty in excludedProperties)
{
var foundKey = schema.properties.Keys.FirstOrDefault(x => string.Equals(x, excludedProperty.Name, StringComparison.CurrentCultureIgnoreCase));
if (!string.IsNullOrEmpty(foundKey))
schema.properties.Remove(excludedProperty.Name);
}
}
#endregion
}
And then in your DTO
[SwaggerExclude] //< --decorate the prop you want to exclude from swagger
public string Value1 { get; set; }
Upvotes: 1