正在从 .net 框架迁移,并正在努力解决响应序列化的差异。
这里的一切似乎都表明默认情况下响应将通过 json 序列化器发出。 https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0但是当返回一个简单的字符串值时,我们所有的端点都具有“text/plain”的内容类型,因此文本不会被引号包围。
给定这个基本 Controller :
[ApiController]
[Route("[controller]")]
public class SanityController : ControllerBase
{
public SanityController()
{
}
[HttpGet0]
public string Get()
{
return "Where are the quotes?";
}
}
还有我们的 Program.cs:
var builder = WebApplication.CreateBuilder(args);
...
// Tried this as well, not sure what the difference even is between this an AddJsonOptions, seemed to work the same.
//builder.Services.Configure<JsonOptions>(options =>
//{
// options.SerializerOptions.IncludeFields = true;
// options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
// options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
// options.SerializerOptions.PropertyNameCaseInsensitive = true;
//});
...
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IncludeFields = true;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
...
app.Run();
但是为所有返回字符串的端点返回的 Content-Type 只是“text/plain”。我们尝试更改客户端上的 Accept header
application/json, text/plain, */*
到 application/json, text/plain;q=0.9, */*;q=0.8
但它仍然会返回文本。只有当我们只将其设置为 application/json
时,它最终才会返回 json。但是,当直接从浏览器窗口点击它时,这并没有帮助,它再次将其返回为“text/plain”。
我们还发现也可以将 [Produces("application/json")]
放在 Controller 方法上,这也可以工作。
但是考虑到 99% 的端点都应该返回 JSON,而几乎没有返回文本或 xml,有没有办法将字符串响应的激进默认值更改为 application/json
app像 ASP.NET 一样宽?
最佳答案
我的方法:
string json = await httpResponseMessage.Content.ReadAsStringAsync();
return new ContentResult()
{
Content = json,
ContentType = "application/json"
};
关于c# - 如何在 ASP.NET Core 7 中以 JSON 形式返回纯字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76518758/