.net core webapi教程-Swagger请求参数设置默认值
本文讲解在使用Swagger进行接口调试时如果给参数设置默认值。
一、准备测试代码
首先创建接口参数接收类SearchReq,代码如下:
namespace NetCoreStudy.Model { public class SearchReq { public string Name { get; set; } public string Description { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } } }
创建接口测试类,代码如下:
using Microsoft.AspNetCore.Mvc; using NetCoreStudy.Model; namespace NetCoreStudy.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class ValuesController : ControllerBase { [HttpPost] public string Test(SearchReq req) { return "ok"+req.Name; } } }
运行调用接口时,string类型的参数默认都是string字符串,数值类型的参数默认值都是0,下面讲解如果给各个参数设置默认值。
二、参数默认值实现方法
首先创建DefaultValueSchemaFilter类并实现ISchemaFilter接口,代码如下:
using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; namespace NetCoreStudy.Config { public class DefaultValueSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { if (schema == null) { return; } var objectSchema = schema; foreach (var property in objectSchema.Properties) { //设置字符串类型参数为""值 if (property.Value.Type == "string" && property.Value.Default == null) { property.Value.Default = new OpenApiString(""); } //设置pageIndex参数默认值为1 if (property.Key == "pageIndex") { property.Value.Default = new OpenApiInteger(1); } //设置pageSize参数默认值为10 else if (property.Key == "pageSize") { property.Value.Default = new OpenApiInteger(10); } } } } }
然后修改Progams.cs文件,代码如下:
builder.Services.AddSwaggerGen(options => { //设置对象类型参数默认值 options.SchemaFilter<DefaultValueSchemaFilter>(); });
访问测试,接口调用传递参数如下图所示:
猜您可能还喜欢
- .net core webapi教程-Swagger请求参数设置默认值(1660)
- .net core webapi教程-设置返回Json格式与Model大小写一致(1141)
- .net core webapi教程-设置日期型字段返回Json格式(1100)
- .net core webapi教程-IActionFilter使用详解 (1057)
- .net core webapi教程-配置 Swagger 显示接口注释及描述信息(1042)
- .net core webapi教程-Swagger请求参数通过属性特性设置默认值(914)
- .net core webapi教程-Filter全局注册、控制器注册如何排除某些Action方法使其不生效(828)
- .net core webapi教程-IExceptionFilter、IAsyncExceptionFilter使用详解 (823)
- .net core webapi教程-使用log4net写文本日志(758)
- .net core webapi教程-使用log4net写sqlserver数据库日志 (693)
评论列表
发表评论
文章分类
文章归档
阅读排行
- 1. Windows Server 2008 R2永久激活及Chew-WGA v0.9下载(12647)
- 2.Visual Studio 2017中安装visualSVN及使用详解(4838)
- 3.完美解决iis下JWplayer提示Error loading media: File could not be played错误(3707)
- 4.asp.net mvc+jquery easyui开发基础(一)模块首页及增加、修改、删除模块实现(2933)
- 5.Android avax.net.ssl.SSLPeerUnverifiedException: No peer certificate 解决方法(httpClient支持HTTPS的访问方式)(2792)
- 6..Net Mvc中使用Jquery EasyUI控件讲解(一)表格控件datagrid使用介绍(2638)
- 7.asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发(三)登录模块开发(2577)
- 8.asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发(七)权限管理模块之系统菜单动态生成(2541)
- 9. asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发(六)权限管理模块之初始数据准备(2191)
- 10.asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发(八)权限管理模块之权限管理实现(2160)