.net core webapi教程-Swagger请求参数通过属性特性设置默认值
深山老妖浏览:9142023-11-30 20:16:45本文累计收益:0我也要赚钱

本文讲解在使用Swagger进行接口调试时如何给参数设置默认值,并且使用请求类属性标记特性的方式赋值默认值。

一、准备测试代码

首先创建接口参数接收类SearchReq,代码如下:

using System.ComponentModel;

namespace NetCoreStudy.Model
{
    public class SearchReq
    {
        [DefaultValue("张三")]
        public string Name { get; set; }
        public string Description { get; set; }
        [DefaultValue(1)]
        public int PageIndex { get; set; }
        [DefaultValue(10)]
        public int PageSize { get; set; }
    }
}

创建接口测试类,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
using System.ComponentModel;
using System.Reflection;

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("");
                }
                //通过属性特性赋值默认值
                DefaultValueAttribute? defaultValueAttribute = context.ParameterInfo?.GetCustomAttribute<DefaultValueAttribute>();
                if (defaultValueAttribute != null) {
                    property.Value.Example = (IOpenApiAny)defaultValueAttribute.Value;
                }
            }
        }
    }
}

然后修改Progams.cs文件,代码如下:

1
2
3
4
builder.Services.AddSwaggerGen(options => {
    //设置对象类型参数默认值
    options.SchemaFilter<DefaultValueSchemaFilter>();
});

访问测试,接口调用传递参数如下图所示:

评论列表
发表评论
+ 关注