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

为何HttpResponseMessage无法获取Azure Function返回的ContentDisposition头?

问题描述

我创建了一个.NET Framework Isolated v4的Azure Function项目,代码如下:

[Function("Function1")]
public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
{
    _logger.LogInformation("C# HTTP trigger function processed a request.");

    var response = req.CreateResponse(HttpStatusCode.OK);

    response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
    response.Headers.Add("Content-Disposition", $@"attachment; filename=""MyFile.txt""");
    response.WriteString("test contents");

    return response;
}

随后创建了一个Blazor WASM .NET 7.0项目,修改FetchData页面代码如下:

protected override async Task OnInitializedAsync()
{
    var content = new StringContent("");

    var response = await Http.PostAsync("http://localhost:7155/api/Function1", content);

    if (response.IsSuccessStatusCode)
    {
        var contentDispositionHeader = response.Content.Headers.ContentDisposition;
        if (contentDispositionHeader != null)
        {
            Console.WriteLine($"Content-Disposition: {contentDispositionHeader.ToString()}");
        }
    }
}

但response.Content.Headers.ContentDisposition始终为null,而Fiddler显示响应头中包含:

Content-Disposition: attachment; filename="MyFile.txt"

请问是什么原因导致HttpResponseMessage无法获取到ContentDisposition头?

原因及解决方法
  • 跨域资源共享(CORS)配置限制:Blazor WASM运行在浏览器环境,属于跨域请求场景。如果Azure Function的CORS配置未明确将Content-Disposition标记为允许暴露给客户端的响应头,浏览器会拦截该头信息,导致.NET HttpClient无法读取。

    • 解决方式:本地调试时,在local.settings.json的CORS配置中添加ExposedHeaders项:
      {
        "Host": {
          "Local": {
            "Cors": {
              "AllowedOrigins": ["http://localhost:5000", "https://localhost:5001"],
              "ExposedHeaders": ["Content-Disposition"]
            }
          }
        }
      }
      
      部署到Azure后,在Function App的CORS设置页面,将Content-Disposition添加到“允许的暴露标头”列表。
  • 响应头归类错误:Content-Disposition属于HTTP内容头范畴,但在代码中直接添加到response.Headers(通用头集合),而.NET HttpClient的response.Content.Headers仅解析归类为内容头的字段。

    • 解决方式:修改Azure Function代码,将Content-Disposition添加到响应的内容头集合:
      var response = req.CreateResponse(HttpStatusCode.OK);
      response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
      // 改为添加到内容头
      response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
      {
          FileName = "MyFile.txt"
      };
      response.WriteString("test contents");
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:13:12