在单个Web API方法上从多个路由中弃用特定路由

时间:2018-02-02 19:58:39

标签: c# asp.net-web-api2 swagger asp.net-core-2.0 asp.net-core-webapi

您好我有WEB API实现,如下所示。我们在单一方法上使用多个路线的地方。

[SwaggerOperation("Update Records By Id")]
    [Route("/construction/field-record")]
    [Route("/construction/fieldRecord")]
    public async Task<IActionResult> UpdateRecord([FromBody] UpdateRecordRequest request)

两个问题,

  1. 如何仅将两个中的一个路由标记为已弃用?
  2. 如何更新swagger,表明路线是&#34;已弃用&#34;在sawagger UI上?
  3. -Thanks

3 个答案:

答案 0 :(得分:5)

作为一种解决方法,你可以这样做

[SwaggerOperation("Update Records By Id")]
[Route("/construction/field-record")]
public async Task<IActionResult> UpdateRecord([FromBody] UpdateRecordRequest request)
{
   // code
}

[SwaggerOperation("Update Records By Id (Deprecated. Use '/construction/field-record')")]
[Route("/construction/fieldRecord")]
[Obsolete("Deprecated. Use 'UpdateRecord'")]
public async Task<IActionResult> UpdateRecordDeprecated([FromBody] UpdateRecordRequest request)
{
    return UpdateRecord(request);
}

答案 1 :(得分:2)

您可以添加用于检查RelativePath的OperationFilter。此字符串包含路线的名称。只需指定HttpPost / HttpGet-routes

[HttpPost("/construction/field-record")]
[HttpPost("/construction/fieldRecord")]

,然后使用以下操作过滤器

public class ExplicitObsoleteRoutes : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (context.ApiDescription.RelativePath.EndsWith("fieldRecord"))
        {
            operation.Deprecated = true;
        }
    }
}

答案 2 :(得分:0)

您可以添加一个OperationFilter来检查OperationId。这是路由的字符串版本,格式一致。参数呈现为“ ByXXXX”,其中XXXX是路径中变量的名称。您可以检查此OperationId以获取要弃用的路由,例如在控制器中:

[HttpGet]
//Obsolete route
[Route("api/customerId}/account/read/{orderId}")]
//Correct route
[Route("api/customerId}/account/{orderId}/read")]

,然后使用操作过滤器:

public class ExplictObsoleteRoutes : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
         if (operation.OperationId.EndsWith("ByOrderIdGet")"))
         {  
             operation.Deprecated = true;
         }
    }
}