AutoRest generation: How to keep a List<int> a List<int> and not List<int?>

Viewed 232

When generating a WebApi with Micrsoft RestClient there are a number of rules to be considered, for example you need to flag all ValueType (like int or System.Guid) as System.ComponentModel.DataAnnotations.RequiredAttribute or else AutoRest will make them System.Nullable<T> in the generated code.

But how do I do this to keep a List<int> a List<int> and not List<int?>? Using [Required]did not help any in this case.

1 Answers

Try registering an ISchemaFilter like so, which should cover both generic collections as well as arrays:

    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        var type = context.Type;

        if (type.IsGenericType && type.GetInterface(nameof(IEnumerable)) != null)
        {
            if (type.GenericTypeArguments.Any(genericTypeArgument => genericTypeArgument.IsValueType)) 
                AddNonNullableFieldToSchema(schema);
        }
        else if (type.IsArray && type.GetElementType()?.IsValueType == true)
        {
            AddNonNullableFieldToSchema(schema);
        }
    }

    private static void AddNonNullableFieldToSchema(OpenApiSchema)
    {
        schema.Items.Extensions["x-nullable"] = new OpenApiBoolean(false);
    }
Related