如何通过XML文档在swagger中设置示例?

时间:2018-10-29 12:10:32

标签: asp.net asp.net-core .net-core swagger swagger-ui

这里是我的注册模型和设置注释的示例,但它仍然没有像这样大张旗鼓地显示 { userName:“字符串” }

而不是 { userName:“茉莉” }

public class RegisterViewModel
    {
        /// <summary>
        /// Name of the user
        /// </summary>
        /// <example>Jasmin</example>
        [Required]
        [Display(Name = "Name")]
        public string UserName { get; set; }

        /// <summary>
        /// User Contact Number
        /// </summary>
        /// <example>9033156314</example>
        [Required]
        [Phone]
        [Display(Name = "PhoneNumber")]
        public string ContactNumber { get; set; }

        /// <summary>
        /// User Device Id
        /// </summary>
        /// <example>12364457tryhret1223</example>
        [Required]
        public string DeviceId { get; set; }

        /// <summary>
        /// User Device Info
        /// </summary>
        /// <example>Jasmin</example>
        [Required]
        public string DeviceInfo { get; set; }
    }

我的方法在下面

/// <summary>
        /// Register User Through Contact Number.
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Register([FromBody]RegisterViewModel model)
        {

}

但示例未显示为大张旗鼓

2 个答案:

答案 0 :(得分:1)

Swashbuckle 4.x的更新,它确实支持使用标记。 (请参阅https://github.com/domaindrivendev/Swashbuckle.AspNetCore

然后我的Startup.cs代码如下

            services.AddSwaggerGen(c =>
            {
                // Set Title and version from config
                c.SwaggerDoc("v1", new Info { Title = "My Title", Version = "1.0", Description = "My Description" });
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                // pick comments from classes, include controller comments: another tip from StackOverflow
                c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
                // enable the annotations on Controller classes [SwaggerTag]
                c.EnableAnnotations();
                // to allow for a header parameter
                c.OperationFilter<AddRequiredHeaderParameter>();
            });

答案 1 :(得分:0)

Swashbuckle不使用<example> XML文档标签。由于没有内置方法,因此必须使用IOperationalFilter手动添加示例。但是,有人可以创建一个更容易使用的NuGet软件包,命名为Swashbuckle.Examples。对于ASP.NET Core项目,实际上需要Swashbuckle.AspNetCore.ExamplesSwashbuckle.AspNetCore.Filters NuGet,具体取决于运行的Swashbuckle.AspNetCore的版本。