Asp.net-Web-Api

Swagger UI:傳遞自定義授權標頭

  • March 10, 2021

我在 ASP.NET Web API 上使用 Swashbuckle 和 Swagger。我正在嘗試找到一種通過 Swagger UI 傳遞包含 Bearer 令牌的 Authorization 標頭的方法。我一直在尋找,但所有的答案似乎都指向這個連結。

但是,這假設標題的內容是預先知道的。我真的需要一種方法來更改 Swagger UI 中的標題(就在點擊“試試看!”按鈕之前),因為 Bearer 令牌每小時都會過期。類似於 Postman 允許您添加標題的方式。

這似乎是一個非常簡單的問題,但答案是什麼?

我們在項目中遇到了同樣的問題。我還想將標頭參數添加到 Swagger UI 網站。這就是我們的做法:

1. 定義一個 OperationFilter 類 OperationFilters 在每次建構 Swagger 時對每個 API 操作執行。根據您的程式碼,將根據您的過濾器檢查操作。在這個例子中,我們讓每個操作都需要 header 參數,但在具有 AllowAnonymous 屬性的操作上讓它成為可選參數。

   public class AddAuthorizationHeader : IOperationFilter
   {
       /// <summary>
       /// Adds an authorization header to the given operation in Swagger.
       /// </summary>
       /// <param name="operation">The Swashbuckle operation.</param>
       /// <param name="schemaRegistry">The Swashbuckle schema registry.</param>
       /// <param name="apiDescription">The Swashbuckle api description.</param>
       public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
       {
           if (operation == null) return;

           if (operation.parameters == null)
           {
               operation.parameters = new List<Parameter>();
           }

           var parameter = new Parameter
           {
               description = "The authorization token",
               @in = "header",
               name = "Authorization",
               required = true,
               type = "string"
           };

           if (apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
           {
               parameter.required = false;
           }

           operation.parameters.Add(parameter);
       }
   }

2.告訴Swagger使用這個OperationFilter 在SwaggerConfig中,只需添加操作過濾器應該使用如下:

   c.OperationFilter<AddAuthorizationHeader>();

希望這可以幫助你!

引用自:https://stackoverflow.com/questions/38906224