ASP.NETCoreWebAPI-如何在Swagger文档中指定必填字段
创始人
2024-09-18 08:01:17
0
  1. 在定义 API 输入模型时,使用 RequiredAttribute 标注必填字段:
public class InputModel
{
    [Required]
    public string RequiredField { get; set; }

    public string OptionalField { get; set; }
}
  1. 使用 Swashbuckle.AspNetCore 库(Swagger 的 .NET 实现)自定义 Schema 操作,将 RequiredAttribute 的信息添加到 Swagger 文档中。

在 Startup.cs 文件中的 ConfigureServices 方法中,添加以下代码:

services.AddSwaggerGen(config =>
{
    // ... [其他 Swagger 配置]

    // 定义一个方法,用于获取指定类型的属性是否必填
    Func isRequiredProperty = (type, propertyName) =>
    {
        var propertyInfo = type.GetProperty(propertyName);
        if (propertyInfo == null) return false;
        return Attribute.IsDefined(propertyInfo, typeof(RequiredAttribute));
    };

    // 使用 Swashbuckle.AspNetCore 库提供的 SchemaFilter 接口
    config.SchemaFilter(isRequiredProperty);

    // ... [其他 Swagger 配置]
});

然后,在当前项目的根目录添加一个 RequiredSchemaFilter.cs 文件,实现 Swashbuckle.AspNetCore 库的 ISchemaFilter 接口:

using System;
using System.Linq;
using System.Reflection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class RequiredSchemaFilter : ISchemaFilter
{
    private readonly Func _isRequiredProperty;

    public RequiredSchemaFilter(Func isRequiredProperty)
    {
        _isRequiredProperty = isRequiredProperty;
    }

    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema == null || context == null || context.Type == null) return;

        foreach (var propertyName in schema.Properties.Keys.ToArray())
        {
            var propertyInfo = context.Type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            if (propertyInfo == null) continue;

            if (_isRequiredProperty(context.Type, propertyName))
            {
                schema.Required.Add(propertyName);
            }

相关内容

热门资讯

科技介绍"欢乐对决辅... 科技介绍"欢乐对决辅助"开挂(软件)辅助软件有挂教学-2026新版总结 【无需打开直接搜索加薇136...
八分钟辅助“凑一桌游戏软件下载... 八分钟辅助“凑一桌游戏软件下载”开挂(软件)辅助软件透牌教程-有挂秘笈>>您好:软件加1367043...
玩家必看分享"新超圣... 您好:这款新超圣辅助器游戏是可以开挂的,确实是有挂的,很多玩家在这款新超圣辅助器游戏中打牌都会发现很...
八分钟辅助“圣游科技辅助器”开... 八分钟辅助“圣游科技辅助器”开挂(安装)辅助安装必备教程-有挂方式;无需打开直接搜索打开薇:1367...
推荐一款"椰子大厅辅... 您好:椰子大厅辅助脚本这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
十分钟辅助“陕西挖坑辅助”开挂... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
透视总结"创思维ap... 透视总结"创思维app有挂吗"开挂(神器)辅助神器存在有挂-详细教程;亲,创思维app有挂吗这款游戏...
五分钟辅助“心悦填大坑辅助器免... 心悦填大坑辅助器免费下载 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理...
一分钟揭秘"微乐小程... 一分钟揭秘"微乐小程序辅助器脚本"开挂(插件)辅助插件确实有挂-新2026版微乐小程序辅助器脚本ai...
教程辅助“微信多乐辅助”开挂(... 教程辅助“微信多乐辅助”开挂(神器)辅助神器插件教程-有挂技术这是一款可以让一直输的玩家,快速成为一...