【问题标题】:How to manually add to swagger's schemas section?如何手动添加到 swagger 的架构部分?
【发布时间】:2020-02-02 00:39:42
【问题描述】:

我正在使用 Swashbuckle.AspNetCore 并开箱即用地获取此架构部分:

我的响应模式看起来是空的,但实际上我返回了子类。如何将它们添加到此部分?

我有这个请求模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using static Assignment_1.AppGlobals;

namespace Assignment_1
{
    public class ExecuteMoveRequest: IValidatableObject, ICloneable
    {
        public int? Move { get; set; }

        [Required]
        public BoardSymbol AzurePlayerSymbol { get; set; }

        [Required]
        public BoardSymbol HumanPlayerSymbol { get; set; }

        [MinLength(9)]
        [MaxLength(9)]
        public BoardSymbol[] GameBoard { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
//...

我将它用于我的响应模型:

using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using static Assignment_1.AppGlobals;

namespace Assignment_1
{
    public interface ExecuteMoveResponse
    {
    }

    [KnownType(typeof(ValidExecuteMoveResponse))]
    public class ValidExecuteMoveResponse: ExecuteMoveRequest, ExecuteMoveResponse
    {
        public string type { get; set; }
    }

    [KnownType(typeof(InProgressExecuteMoveResponse))]
    public class InProgressExecuteMoveResponse : ValidExecuteMoveResponse
    {
    }

    [KnownType(typeof(WonExecuteMoveResponse))]
    public class WonExecuteMoveResponse : ValidExecuteMoveResponse
    {
        [Required]
        public BoardSymbol Winner { get; set; }
        [Required]
        public int[] WinPositions { get; set; }
    }
}

【问题讨论】:

    标签: c# asp.net-core swagger swashbuckle


    【解决方案1】:

    首先尝试将这些类分开在不同的文件中。 第二次尝试在你的课程之前添加这个 cmets:

    /// <summary>
    /// Description for Your class
    /// </summary>
    [KnownType(typeof(InProgressExecuteMoveResponse))]
    public class InProgressExecuteMoveResponse : ValidExecuteMoveResponse
    {
        ...
    }
    

    在某些情况下显示摘要您必须在 swashbuckle 配置中启用它。 也尝试用这种方式配置 Swashbuckle:

      app.UseSwaggerUi3WithApiExplorer(settings =>
            {
                settings.GeneratorSettings.DefaultEnumHandling = EnumHandling.String;
                settings.GeneratorSettings.AllowReferencesWithProperties = true;
    ...
    

    【讨论】:

    • “您必须在 swashbuckle 配置中启用它” - 这是什么意思?我不是在写一个 MVC 应用程序我在写一个 web api 应用程序,顺便说一句。我的启动/配置有:app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint($"/swagger/{SWAGGER_API_VERSION}/swagger.json", $"{SWAGGER_API_TITLE} {SWAGGER_API_VERSION}"); // Serve the Swagger UI at the app's root (http://localhost:&lt;port&gt;) c.RoutePrefix = string.Empty; });
    • 感谢您提供的详细信息,顺便说一句 - 应该事先感谢您 :) 我只是忘记了,因为我无法让它工作
    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    相关资源
    最近更新 更多