C# Azure Function调试返回406 Not Acceptable问题求助
Azure Function HTTP触发器返回406 Not Acceptable修复方案
问题场景
对接外部API开发的Azure Function HTTP触发器代码如下:
public static async Task<HttpResponse> RunProduction( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { _log = log; API_URL = @"{API_URL}"; BEARER_TOKEN = Environment.GetEnvironmentVariable("{ENV_NAME}"); if (BEARER_TOKEN.Equals("")) throw new Exception("Bearer token could not be retrieved"); var response = req.HttpContext.Response; response.Clear(); response.StatusCode = 200; response.ContentType = "text/plain"; //This is where the API will be called. //The method is not changing anything in the response (yet) response = await ExecuteMethods(req, response); return response; }
本地使用Postman测试时已配置对应请求头:
即使注释掉ExecuteMethods()调用行,请求仍持续返回406 Not Acceptable错误,目标是修复问题让接口正常返回200状态码。
根因说明
406错误是HTTP内容协商校验失败导致,核心问题是代码写法违反了Azure Function HTTP触发器的响应处理规则:
- 直接从
req.HttpContext获取原始响应对象修改后返回,完全绕过了Azure Functions运行时的响应处理管道 - 运行时收到返回的原始Response对象时,会根据请求携带的
Accept头做内容匹配校验,直接给原始Response设置的ContentType不会被运行时识别,校验不通过就直接返回406,和内部业务逻辑是否执行无关 - 额外隐患:将日志实例、API地址、Token存在静态变量的写法存在线程安全风险,并发请求时会出现值被覆盖的问题。
修复步骤
- 移除所有直接操作
req.HttpContext.Response的逻辑,所有响应对象必须通过触发器请求参数提供的CreateResponse方法构造,让运行时能正确识别响应元数据,完成内容协商校验。 - 取消静态变量存储上下文、配置的写法,每次调用直接从方法参数、环境变量读取对应值,避免并发问题。
修复后参考代码(进程内模型In Process)
public static async Task<HttpResponseMessage> RunProduction( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("Production function processed a request."); var apiUrl = Environment.GetEnvironmentVariable("API_URL"); var bearerToken = Environment.GetEnvironmentVariable("BEARER_TOKEN_ENV_NAME"); if (string.IsNullOrEmpty(bearerToken)) { return req.CreateResponse(System.Net.HttpStatusCode.InternalServerError); } var response = req.CreateResponse(System.Net.HttpStatusCode.OK); response.Content = new StringContent("", Encoding.UTF8, "text/plain"); // 原有API调用逻辑 response = await ExecuteMethods(req, response); return response; }
如果你使用的是独立工作进程模型(Isolated Worker Model),将参数替换为
HttpRequestData和FunctionContext,通过req.CreateResponse()构造响应即可,核心逻辑一致。
- 快速验证方式:Postman测试时临时将请求头的
Accept值设为*/*,修复完成后即使指定特定Accept类型也不会返回406错误。
内容的提问来源于stack exchange,提问作者TBatist
相关产品推荐
相关产品推荐

