You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Asp.Versioning.Mvc在ASP.NET Core Web API中弃用指定Action

实现ASP.NET Core Web API中特定Action的版本弃用

在使用Asp.Versioning.Mvc包时,要弃用控制器中的单个Action而非整个控制器,只需给目标Action添加**[Deprecated]特性**即可,具体实现如下:

核心操作步骤

  • 确保项目已正确引入Asp.Versioning.Mvc包,且全局API版本控制服务已完成注册(例如在Program.cs中配置)。
  • 在需要弃用的Action上添加[Deprecated]特性,可通过参数指定该Action对应的弃用版本。若Action单独标记了[ApiVersion],需保证弃用版本与Action的API版本匹配。

代码示例

假设你有TestController,其中包含需弃用的Get方法和正常保留的GetAll方法,代码示例如下:

using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/v{version:apiVersion}/test")]
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public class TestController : ControllerBase
{
    // 弃用1.0版本的Get方法
    [HttpGet("{id}")]
    [ApiVersion("1.0")]
    [Deprecated(version: "1.0")]
    public IActionResult Get(int id)
    {
        return Ok(new { Id = id, Message = "该Get方法已弃用(v1.0)" });
    }

    // 2.0版本的Get方法正常生效
    [HttpGet("{id}")]
    [ApiVersion("2.0")]
    public IActionResult GetV2(int id)
    {
        return Ok(new { Id = id, Message = "当前生效的Get方法(v2.0)" });
    }

    // 全版本的GetAll方法正常保留
    [HttpGet]
    public IActionResult GetAll()
    {
        return Ok(new[] { new { Id = 1 }, new { Id = 2 } });
    }
}

效果验证

当客户端调用api/v1.0/test/1时,响应头会自动返回api-deprecated-versions: 1.0;而调用api/v1.0/test(GetAll方法)或api/v2.0/test/1时,不会出现该弃用响应头,完全符合预期。

额外说明

  • 若需给弃用Action添加自定义提示,可使用[Deprecated]的Message参数,例如:[Deprecated(version: "1.0", Message = "请使用v2.0版本的Get方法")],该信息会同步显示在API文档(如Swagger)中。
  • 若Action未单独标记[ApiVersion],[Deprecated]会默认作用于控制器的所有版本,此时需明确指定版本范围,避免误影响其他版本的Action。

内容的提问来源于stack exchange,提问作者Dilakshan AT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 00:04:55