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

Azure Function添加Deprecated API响应头的实现方案问询

刚好之前处理过类似的Azure Function弃用场景,给你整理一下正确的实现方式和需要注意的点!

实现Azure Function的弃用警告头设置

首先,你需要确保在HttpResponseMessage中正确添加Warning头,同时考虑代理环境下的头传递问题。下面是完整的代码示例(基于.NET in-process模型):

[FunctionName("MyAPI")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
    ILogger log)
{
    log.LogInformation("Received request for deprecated API - logging for migration tracking.");

    // 构建你的业务响应内容,同时加入弃用提示
    var apiResponse = new { 
        Data = "Your existing response data",
        DeprecationNotice = "This API will be retired on 2024-12-31. Please use the new /v2/MyAPI endpoint instead."
    };

    // 创建响应对象
    var response = req.CreateResponse(HttpStatusCode.OK, apiResponse);

    // 添加标准格式的Warning头
    // 格式说明:警告码 + 空格 + 代理名称(用"-"表示无特定代理) + 空格 + 带引号的警告信息
    response.Headers.Add("Warning", @"299 - ""Deprecated API: This endpoint will be retired on 2024-12-31""");

    // 针对代理环境的额外配置:避免代理缓存旧响应,确保警告头实时传递
    response.Headers.CacheControl = new CacheControlHeaderValue
    {
        NoCache = true,
        NoStore = true,
        MustRevalidate = true
    };

    return response;
}

关键注意事项

  • 代理环境的头传递:因为你的Function部署在代理后方,一定要检查代理的配置(比如Azure Application Gateway、API Management等),确保Warning头没有被代理过滤。如果代理有响应头白名单,需要将Warning添加到允许列表中。
  • 状态码的选择:299是自定义的警告状态码,属于非标准但广泛使用的弃用提示码。如果需要更标准的HTTP状态,可以考虑:
    • 301 Moved Permanently:直接重定向到新API(适合已经完全替代的场景)
    • 410 Gone:表示API已永久移除(适合弃用后期)
    • 200 OK + Warning头:适合过渡期,告知用户但仍返回正常数据
  • 多渠道提示:除了响应头,建议在响应体中也明确添加弃用通知,这样即使客户端忽略响应头,用户也能看到提示信息。
  • 日志统计:通过ILogger记录所有访问该弃用API的请求,包括客户端IP、请求时间等信息,帮助你统计用户迁移进度,确定最终的下线时间。

如果使用.NET Isolated模型

如果你的Azure Function是用.NET Isolated(进程外)模型开发的,代码写法略有不同:

[Function("MyAPI")]
public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
    FunctionContext executionContext)
{
    var logger = executionContext.GetLogger("MyAPI");
    logger.LogInformation("Received request for deprecated API.");

    var response = req.CreateResponse(HttpStatusCode.OK);
    response.Headers.Add("Warning", @"299 - ""Deprecated API: Retiring on 2024-12-31""");
    
    var apiResponse = new {
        Data = "Your response content",
        DeprecationInfo = "Use /v2/MyAPI for future requests"
    };
    await response.WriteAsJsonAsync(apiResponse);

    // 配置缓存控制确保代理不缓存
    response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");

    return response;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:23:09