为何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项:
部署到Azure后,在Function App的CORS设置页面,将{ "Host": { "Local": { "Cors": { "AllowedOrigins": ["http://localhost:5000", "https://localhost:5001"], "ExposedHeaders": ["Content-Disposition"] } } } }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");
- 解决方式:修改Azure Function代码,将
内容的提问来源于stack exchange,提问作者Mister Cook
相关产品推荐
相关产品推荐

