正如Kiran Challa 在对 OP 的评论中提到的,样本的自动生成是帮助页面包的一部分,而不是 ApiExplorer 接口。
对于问题 #1,您希望为复合对象定义示例,无论它们在哪里使用。您可以通过帮助页面配置中的 SetSampleObjects 方法执行此操作。例如,这是来自我的 HelpPageConfig.Register 方法:
config.SetSampleObjects(new Dictionary<Type, object>
{
{typeof(CompositeType1), ModelExamples.GenerateExample<CompositeType1>()},
{typeof(CompositeType2), ModelExamples.GenerateExample<CompositeType2>()},
{typeof(CompositeType3), ModelExamples.GenerateExample<CompositeType3>()},
});
其中 ModelExamples.GenerateExample 是我用来创建指定类型的示例对象的静态方法/类,以保持本节简洁明了。以上将导致您的帮助页面文档将您生成的示例用于 CompositeType1、CompositeType2 和 CompositeType3 的返回类型。
这让我们想到了问题 #2。我假设您正在谈论由多种复合类型组成的返回类型,例如:
List<CompositeType1>
或
Tuple<CompositeType1,CompositeType2>
仅使用上述生成的模型是不够的,因为帮助页面逻辑仅在决定是使用您的模型还是生成通用示例之前检查整个返回的类型。所以你需要添加这样的条目:
config.SetSampleObjects(new Dictionary<Type, object>
{
{
typeof(List<CompositeType1>),
ModelExamples.GenerateExample<List<CompositeType1>>()
},
{
typeof(Tuple<CompositeType1,CompositeType2>),
ModelExamples.GenerateExample<Tuple<CompositeType1,CompositeType2>>()
},
});
现在,如果您将 HttpResponseMessage 用于任何返回类型,那就是当您像这样使用 config.SetActualResponseType() 时:
config.SetActualResponseType(
typeof(List<CompositeType1>),
"Foo",
"ApiMethodA");
config.SetActualResponseType(
typeof(Tuple<CompositeType1,CompositeType2>),
"Bar",
"ApiMethodB");
TL;DR / 结论: config.SetSampleObjects 和 config.SetActualResponseType 的组合可以让您自定义帮助页面自动生成文档中示例对象的外观,并允许您指定每个方法的响应应该使用哪些示例对象。
2016 年编辑 回复评论。 ModelExamples 只是创建指定类型的示例对象。这可以通过多种方式完成,但这里有一种方式:
public static class ModelExamples
{
public static T GenerateExample<T>()
{
var retval = default(T);
if (typeof(T) == typeof(ActionResult))
{
var value = ActionResult.Success;
retval = (T)(object)value;
}
// ... whatever other types you handle go here ...
return retval;
}
}