gpt4 book ai didi

asp.net-web-api - Web Api - 使用 ApiExplorer 自动生成请求示例

转载 作者:行者123 更新时间:2023-12-02 05:54:44 26 4
gpt4 key购买 nike

有没有办法让 ApiExplorer 自动生成请求样本?

我尝试使用:

config.SetActualResponseType(typeof(SomeType), "ControllerName", "Post"); 

在HelpPageConfig.cs中,但出现了2个问题:

  1. 它要求我为特定 Controller 和操作定义特定类型,并且我正在寻找更通用的东西,如果满足以下条件,则不需要添加\更改代码添加了新的 Controller \类型。

  2. 每个 Controller \操作只能使用一种类型,因此我无法为在其请求正文中接收 2 个复合类型的操作生成完整的请求示例。

关于如何解决\处理这些问题有什么想法吗?

最佳答案

Kiran Challa在 OP 的评论中提到,自动生成示例是帮助页面包的一部分,而不是 ApiExplorer 界面。

对于问题#1,您希望为复合对象定义示例,无论它们在何处使用。您可以通过帮助页面配置中的 SetSampleObjects 方法来执行此操作。例如,这是来 self 的 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;
}
}

关于asp.net-web-api - Web Api - 使用 ApiExplorer 自动生成请求示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18810936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com