簡體   English   中英

如何告訴Swagger不要在輸入類中將某些字段顯示為參數?

[英]How can I tell Swagger to not show certain fields in my input class as parameters?

我有一個api應用,其中控制器方法將一個類作為輸入。 我正在使用Swagger向用戶顯示該類中的變量。 我將該類用於其他目的,因此對於某些方法,我希望Swagger不顯示某些對象。 我嘗試了此處提到的[IgnoreDataMember]屬性,但似乎沒有任何作用。 如何防止Swagger顯示輸入類中的每個對象?

所以這是方法定義:

[HttpPost("Receive")]
[Produces("application/json", Type = typeof(APIResponse))]
public APIResponse Receive(MyClass item)
{....}

MyClass定義了4個對象:

public class MyClass
{
    [IgnoreDataMember]
    public int itemID { get; set; }
    [IgnoreDataMember]
    public int quantity { get; set; }
    public int vendor_id { get; set; }
    public string ship_name { get; set; }
}

現在,Swagger將所有4個對象顯示為參數:

在此處輸入圖片說明

對於此方法,我只想顯示4個類對象中的2個作為參數。 對於其他方法,我將需要顯示全部4。是否可以執行此操作?還是需要為每個方法創建一個類?

默認情況下, Swagger不准備這樣做,如果您想要一個參數,可以添加一個默認值,例如

public void myMethod(string a = "abc", int a = 1)

但是,如果您想完全省略一個參數,可以進行如下修改:

添加一個名為CustomSchemaFilters的新文件

public class CustomSchemaFilters : ISchemaFilter
{
    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
        var excludeProperties = new[] {"name", "lastname, "token"};

        foreach(var prop in excludeProperties)
            if (schema.properties.ContainsKey(prop))
                schema.properties.Remove(prop);
    }
}

並在文件AppStart / SwaggerConfig.cs中

並在同一文件中添加這一行

c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

就在里面:

GlobalConfiguration.Configuration .EnableSwagger(c => { ...

添加行:

c.SchemaFilter<CustomSchemaFilters>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM