[英]How to deal with swagger against route overrides?
我正在嘗試將 Swagger 嵌入到我的 Asp Core (.Net 6) 項目中,其中存在一些路由覆蓋的情況。 但是,即使在以下情況下,我面臨的問題也可以重現。
考慮一個最小的 Asp Core (.Net 6) 應用程序。 例如,就像 Swashbuckle 用作測試的那樣: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/tree/master/test/WebSites/MinimalApp
現在,考慮同一個應用程序中的兩個控制器:
[ApiController]
[Route("/api")]
public class MyFallbackController : ControllerBase
{
[HttpGet("values", Order = 1)]
public ActionResult<object> GetValues()
{
return new[] { 1, 2, 3 };
}
}
[ApiController]
[Route("/api")]
public class MyOverrideController : ControllerBase
{
[HttpGet("values", Order = 0)]
public ActionResult<object> GetValues()
{
return new[] { 4, 5, 6 };
}
}
請注意,路線完全相同,但只考慮第一個( Order = 0
)。
如果我運行應用程序並導航到:
https://localhost:7263/api/values
響應給出了預期的結果: [4, 5, 6]
但是,當我嘗試訪問 Swagger 部分時,它不起作用,因為(顯然)它顯示為 controller 對的碰撞:
處理請求時發生未處理的異常。
SwaggerGeneratorException:用於操作的沖突方法/路徑組合“GET api/values” - WebApplication2.MyFallbackController.GetValues (WebApplication2)、WebApplication2.MyOverrideController.GetValues (WebApplication2)。 操作需要 Swagger/OpenAPI 3.0 的唯一方法/路徑組合。 使用 ConflictingActionsResolver 作為解決方法
有沒有辦法擺脫這個問題?
找到了。
順便說一句,正如異常消息所暗示的那樣,訣竅在於SwaggerGen
配置。
using Microsoft.AspNetCore.Mvc.ApiExplorer;
services.AddSwaggerGen(c =>
{
c.ResolveConflictingActions(apiDescriptions =>
{
int best_order = int.MaxValue;
ApiDescription? best_descr = null;
foreach (var curr_descr in apiDescriptions)
{
int curr_order = curr_descr.ActionDescriptor.AttributeRouteInfo?.Order ?? 0;
if (curr_order < best_order)
{
best_descr = curr_descr;
}
}
return best_descr;
});
});
基本上,上面的 function 只選擇重復項中順序最低的ApiDescription
。
這是我幼稚但有效的解決方案。 例如,我不知道輸入集合是否已經按順序排序。 在這種情況下,代碼可能會更簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.