【问题标题】:AutoRest generation: How to keep a List<int> a List<int> and not List<int?>AutoRest 生成:如何将 List<int> 保留为 List<int> 而不是 List<int?>
【发布时间】:2020-07-03 20:53:26
【问题描述】:

当使用 Micrsoft RestClient 生成 WebApi 时,需要考虑许多规则,例如,您需要将所有 ValueType(如 intSystem.Guid)标记为 System.ComponentModel.DataAnnotations.RequiredAttribute,否则 AutoRest 会生成它们System.Nullable&lt;T&gt; 在生成的代码中。

但是我该如何做才能保留List&lt;int&gt;List&lt;int&gt; 而不是List&lt;int?&gt;?在这种情况下,使用[Required]没有任何帮助。

【问题讨论】:

    标签: c# asp.net-web-api autorest


    【解决方案1】:

    尝试像这样注册一个 ISchemaFilter,它应该涵盖泛型集合和数组:

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

    【讨论】:

    • AddNonNullableFieldToSchema(schema) 会发生什么?
    • 已编辑以包含缺少的方法,对此感到抱歉。
    • 谢谢,我试试看。
    • 不幸的是,它似乎不起作用。我试过用这个迷你控制器:public class ValuesController : ApiController { [SwaggerResponse(HttpStatusCode.OK, Type = typeof(MyResponse))] public IHttpActionResult GetStuff() { return Ok(new MyResponse()); } } public class MyResponse { [Required] public int Hotz { get; set; } public List&lt;int&gt; Hurz { get; set; } }Apply() 只被称为 IHttpActionResultMyResponse 而不是 List&lt;int&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    相关资源
    最近更新 更多