Web Api 2:"样本不可用"

Jen*_*112 12 asp.net web asp.net-web-api asp.net-web-api2

我正在尝试为我的Web Api自动生成帮助文档.

但是我在一个特定方法上看到无法生成样本请求,如图所示:

此搜索

以下是参数请求参数:

镜像2

为什么无法生成样本请求格式?

Chr*_*ris 14

我发现返回的动作IHttpActionResult有一个缺失的样本.为了获得为这些方法生成的样本,我不得不用a来装饰动作ResponseTypeAttribute,例如:

[ResponseType(typeof(Model))]
public async Task<IHttpActionResult> Get(int key)
{
    var entity = await dbContext.Models.FindAsync(key);

    if (entity == null)
    {
        return NotFound();
    }

    return Ok(entity);
}
Run Code Online (Sandbox Code Playgroud)


小智 7

确保您创建的任何对象都有一个空构造函数.Web API帮助页面无法"自动"创建没有空构造函数的对象.如果不能创建空构造函数,则可以使用config.SetSampleObjects"手动"创建它们


Chr*_*is_ 5

对于任何好奇@chris 和@wade-wright 之间的答案中哪一个是正确的人。

答案是两者都有。两者都是必需的。例如,如果您正在使用 VM 将 API 返回的内容合并到必要的数据中,您可能会考虑执行以下操作:

[ResponseType(typeof(YourVM))]
Run Code Online (Sandbox Code Playgroud)

超越你的控制器操作

以及虚拟机中的空构造函数:

 public class YourVM
    {
        public YourVM() { }
    }
Run Code Online (Sandbox Code Playgroud)