如何将Azure Function返回响应的Content-Type设置为application/json?
解决Azure Function响应Content-Type为text的问题
你可以通过两种方式修改代码,将响应的Content-Type设置为application/json:
方法一:直接设置响应头
在创建响应后,手动指定Content-Type头部信息:
if (request.IsSuccessStatusCode) { content = await request.Content.ReadAsStringAsync(); var response = req.CreateResponse(request.StatusCode); // 设置响应的Content-Type为JSON格式 response.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); await response.WriteStringAsync(content); return response; }
方法二:使用StringContent构建响应内容
直接用StringContent包装返回的JSON字符串,并指定媒体类型,再赋值给响应的Content属性:
if (request.IsSuccessStatusCode) { content = await request.Content.ReadAsStringAsync(); var response = req.CreateResponse(request.StatusCode); // 用StringContent指定编码和媒体类型 response.Content = new StringContent(content, Encoding.UTF8, "application/json"); return response; }
说明
原来的代码使用WriteStringAsync时,默认不会指定Content-Type,框架会自动设为text/plain。通过上述两种方式明确指定媒体类型后,Postman中就能识别响应为JSON格式了。
内容的提问来源于stack exchange,提问作者Jason_Hough
相关产品推荐
相关产品推荐

