将content-type设置为application/json

huangapple go评论78阅读模式
英文:

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,因为它是作为文本返回的。

如下图所示:

将content-type设置为application/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:

将content-type设置为application/json

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.

huangapple
  • 本文由 发表于 2023年7月18日 00:22:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76706401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定