如何在.net api文档中显示自定义请求示例?

时间:2019-02-27 10:25:40

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

    /// <summary>
    /// updates information of a job
    /// </summary>
    /// <param name="job"></param>
    /// <returns>Ok or Error</returns>
    /// <example>
    /// {
    ///     "info_id": 1,
    ///     "some_other_id": 2
    /// }
    /// </example>
    [HttpPost]
    [Route("api/job/update")]
    public IHttpActionResult update(Models.Job job) {
    }

    //the model
    public class Job {
        [Required(AllowEmptyStrings = false)]
        [Range(1, Int64.MaxValue)]
        public Int64 info_id { get; set; }
        public Int64? some_other_id{ get; set; }
        public DateTime last_log_time { get; set; }
    }

想象一下上面的设置。我想展示在文档中update的doc块内编写的示例JSON。但是,显示的是类型为Job的对象的序列化JSON,带有默认值。

enter image description here

我不希望开发人员认为他们可以或应该提供last_log_time来运行update。此属性应显示在响应消息中,但不发送给api。
如何为每个函数的请求格式自定义示例?理想情况下,我会如图所示在doc块中声明它(API应该仅接受JSON格式的请求),或者按照Job类的属性上的注释进行声明。

How can we hide a property in WebAPI?这里提供的答案无济于事,因为如上所述,应在回复中给出last_log_time。如果我用[IgnoreDataMember]进行注释,它将被全局忽略。

1 个答案:

答案 0 :(得分:0)

您可以将[ApiExplorerSettings(IgnoreApi = true)]添加到last_log_time属性中,但只会在主体参数中隐藏last_log_time。

如果要以示例格式隐藏,则需要在文件WriteSampleObjectUsingFormatter上自定义方法Areas\HelpPage\SampleGeneration\HelpPageSampleGenerator.cs的源代码