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

.NET 6 API版本控制:未指定用默认,无效版本需返回错误

解决方案

要实现你需要的版本控制逻辑——未指定版本时用默认值,指定不支持版本时返回错误,需要调整ApiVersioning的配置并添加自定义逻辑,具体步骤如下:

1. 调整基础ApiVersioning配置

首先关闭AssumeDefaultVersionWhenUnspecified(该配置会将无法识别的版本也视为未指定),同时明确版本读取方式和支持的版本:

services.AddApiVersioning(opt =>
{
    opt.DefaultApiVersion = new ApiVersion(2, 0);
    // 关闭自动将未识别版本转为默认版本的行为
    opt.AssumeDefaultVersionWhenUnspecified = false;
    // 开启版本报告,便于客户端了解支持的版本
    opt.ReportApiVersions = true;
    // 指定从Content-Type头的"v"参数读取版本
    opt.ApiVersionReader = new MediaTypeApiVersionReader("v");
})
.AddMvc(options =>
{
    // 注册自定义过滤器处理未指定版本的场景
    options.Filters.Add(new DefaultApiVersionFilter(new ApiVersion(2, 0)));
});

2. 实现自定义过滤器处理未指定版本

创建一个动作过滤器,当请求未携带任何版本信息时,手动将版本设置为默认值:

public class DefaultApiVersionFilter : IActionFilter
{
    private readonly ApiVersion _defaultVersion;

    public DefaultApiVersionFilter(ApiVersion defaultVersion)
    {
        _defaultVersion = defaultVersion;
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        var versionFeature = context.HttpContext.Features.Get<IApiVersioningFeature>();
        
        // 若请求未指定版本,设置为默认版本
        if (versionFeature?.RequestedApiVersion == null)
        {
            versionFeature.RequestedApiVersion = _defaultVersion;
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // 无需后续处理
    }
}

3. 自定义版本验证器返回415错误

默认情况下,指定不支持的版本会返回400 Bad Request,若要返回UnsupportedMediaType(415),可以自定义版本验证器:

public class StrictApiVersionValidator : IApiVersionValidator
{
    public void Validate(ApiVersionValidatorContext context)
    {
        var requestedVersion = context.RequestedApiVersion;
        var supportedVersions = context.SupportedApiVersions;

        // 若请求指定了版本但不在支持列表中,返回415错误
        if (requestedVersion != null && !supportedVersions.Contains(requestedVersion))
        {
            context.Result = new UnsupportedMediaTypeResult();
        }
    }
}

然后在ApiVersioning配置中注册该验证器:

services.AddApiVersioning(opt =>
{
    // ... 保留之前的配置 ...
    // 使用自定义验证器
    opt.ApiVersionValidator = new StrictApiVersionValidator();
})
// ... 保留Mvc过滤器配置 ...

最终效果验证

  • Content-Type: application/json;v=1.0 → 匹配API版本1.0
  • Content-Type: application/json;v=2.0 → 匹配API版本2.0
  • Content-Type: application/json → 自动使用默认版本2.0
  • Content-Type: application/json;v=3.0 → 返回415 Unsupported Media Type

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:25:22