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);
            }

相关内容

热门资讯

WePoKe透视挂!红龙扑克模... WePoKe透视挂!红龙扑克模拟器,(aa poker)原来存在有挂(详细透视力荐教程),支持语音通...
透视免费(德州免费辅助神器ap... 透视免费(德州免费辅助神器app)wepokeai代打(详细辅助微扑克教程)本来真的有挂1、在德州免...
透视好友房(wepOkE)外挂... 透视好友房(wepOkE)外挂透明挂辅助代打(wepoke模拟器)一直存在有挂(详细透视攻略方法);...
wepokeai代打!德扑之星... wepokeai代打!德扑之星记分牌有什么用,(aa poker)真是真的有挂(详细辅助科技教程);...
透视数据(德州ai机器人)nz... 透视数据(德州ai机器人)nzt德州辅助(详细辅助切实教程)都是真的是有挂1、许多玩家不知道德州ai...
透视苹果版(wePoke)透视... 1、透视苹果版(wePoke)透视辅助安装(wepok软件透明挂)确实是有挂(详细透视高科技教程)(...
wpk辅助挂!德州辅助软件开发... wpk辅助挂!德州辅助软件开发定制,(wePOke)一向真的是有挂(详细辅助插件教程);wpk辅助挂...
透视辅助(微扑克ai辅助)微扑... 透视辅助(微扑克ai辅助)微扑克ai辅助器苹果版(详细辅助黑科技教程)一直存在有挂是一款可以让一直输...
透视中牌率(WePoke)外挂... 1、透视中牌率(WePoke)外挂透明挂辅助器(wepoke一定有挂)原生真的是有挂(详细透视202...
wepoke黑科技!轰趴大菠萝... wepoke黑科技!轰趴大菠萝辅助器,(wEpOke)起初存在有挂(详细透视透视教程);人气非常高,...