.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请求参数设置默认值(1897)
- .net core webapi教程-设置返回Json格式与Model大小写一致(1323)
- .net core webapi教程-设置日期型字段返回Json格式(1243)
- .net core webapi教程-配置 Swagger 显示接口注释及描述信息(1223)
- .net core webapi教程-IActionFilter使用详解 (1168)
- .net core webapi教程-Swagger请求参数通过属性特性设置默认值(1033)
- .net core webapi教程-Filter全局注册、控制器注册如何排除某些Action方法使其不生效(1016)
- .net core webapi教程-IExceptionFilter、IAsyncExceptionFilter使用详解 (978)
- .net core webapi教程-Filter的多种注册方法(928)
- .net core webapi教程-使用log4net写文本日志(896)
评论列表
发表评论
文章分类
文章归档
阅读排行
- 1. Windows Server 2008 R2永久激活及Chew-WGA v0.9下载(13254)
- 2.Visual Studio 2017中安装visualSVN及使用详解(5187)
- 3.完美解决iis下JWplayer提示Error loading media: File could not be played错误(4041)
- 4.asp.net mvc+jquery easyui开发基础(一)模块首页及增加、修改、删除模块实现(3353)
- 5.Android avax.net.ssl.SSLPeerUnverifiedException: No peer certificate 解决方法(httpClient支持HTTPS的访问方式)(3211)
- 6..Net Mvc中使用Jquery EasyUI控件讲解(一)表格控件datagrid使用介绍(2981)
- 7.asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发(三)登录模块开发(2879)
- 8.asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发(七)权限管理模块之系统菜单动态生成(2855)
- 9.asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发(八)权限管理模块之权限管理实现(2462)
- 10. asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发(六)权限管理模块之初始数据准备(2452)
