英文:
Setting content-type to application/json
问题
我有这个C#代码在我的Azure函数中:
var data = new StringContent(requestBody, Encoding.UTF8, "application/json");
var request = await GetSubmissions.PostAsync("url", data);
if (request.IsSuccessStatusCode)
{
content = await request.Content.ReadAsStringAsync();
var response = req.CreateResponse(request.StatusCode);
await response.WriteStringAsync(content);
return response;
}
这个代码从API调用中接收数据,然后将其作为Azure函数的响应返回。一切都很好,我可以在Postman中正常看到它被返回,但我需要将响应中的内容类型更改为JSON,因为它是作为文本返回的。
如下图所示:
你可以尝试下一步做什么呢?
英文:
I have this C# code in my Azure function:
var data = new StringContent(requestBody, Encoding.UTF8, "application/json");
var request = await GetSubmissions.PostAsync("url", data);
if (request.IsSuccessStatusCode)
{
content = await request.Content.ReadAsStringAsync();
var response = req.CreateResponse(request.StatusCode);
await response.WriteStringAsync(content);
return response;
}
This receives data from an API call, and then returns it as response from that Azure function. All is good and I can see it being returned in Postman just fine, but I need to change the content type to JSON within the response as it is coming in as text.
As shown in this screenshot:
What can I try next?
答案1
得分: 1
尝试明确设置响应头:
response.Headers.Add("Content-Type", "application/json; charset=utf-8");
另一种选项(虽然不太推荐)是将响应反序列化,然后使用 WriteAsJsonAsync
再次序列化它。
英文:
Try explicitly setting the response header:
response.Headers.Add("Content-Type", "application/json; charset=utf-8");
Another option (though less preferable one) would be to deserialize the response and then serialize it back with WriteAsJsonAsync
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论