2017-08-24 92 views
0

我已经按照this教程为Swagger帮助页面设置了Swashbuckle的自定义放大器请求示例。SwaggerRequestExample在使用列表时抛出错误

它工作正常时,API接受一个对象作为身体的说法,但使用列表时,我得到一个“对象不设置到对象的实例”异常

这里是一个代码示例

using Swashbuckle.Examples; 

[HttpPost] 
[SwaggerRequestExample(typeof(List<TestModel>), typeof(TestExample))]  
public IHttpActionResult ListTest([FromBody] List<TestModel> tests) 
{ 
    return Ok(tests); 
} 

public class TestExample : IExamplesProvider 
{ 
    public object GetExamples() 
    { 
     return new List<TestModel>() { 
      new TestModel() 
      { 
       Id = 1, 
       Text = "First object" 
      }, 
      new TestModel() 
      { 
       Id = 2, 
       Text = "Second object" 
      }, 
     }; 
    } 
} 

任何帮助,将不胜感激

+0

@HelderSepu TestModel只是一个示例模型,它有两个属性int Id和string Text。我使用的模型要复杂得多,但错误是一样的,所以我不认为模型是问题。 - 如果我删除了SwaggerRequestExample?是的,那么它不会抛出错误。但后来我只是得到了自动生成的示例请求,这是我不想要的,也是我使用SwaggerRequestExample的原因。 – David

+0

@HelderSepu正确,不同之处在于这是requestexample,而不是responseexample,请求是列表 – David

+0

@HelderSepu是的正确,唯一的区别是你的请求是单个对象 – David

回答

0

随着@HelderSepu建议使用ApplySchemaVendorExtensions,这是我做的,使其工作:

在我SwaggerConfig.cs

c.SchemaFilter<ApplySchemaVendorExtensions>(); 

ApplySchemaVendorExtensions.cs

using Swashbuckle.Swagger;  
public class ApplySchemaVendorExtensions : ISchemaFilter 
{ 
    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type) 
    { 
     if (schema.properties != null) 
     { 
      if (type == typeof(TestModel)) 
      { 
       schema.example = new TestModel() 
       { 
        Id = 1, 
        Text = "Custom text value" 
       }; 
      } 
     } 
    } 
} 

我不会万一有人却标记为答案有一个更好的解决方案。