在从 .net 框架迁移的过程中,正在努力解决响应序列化的差异。
这里的所有内容似乎都表明默认情况下响应将通过 json 序列化器发出。https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0但是当返回一个简单的字符串值时,我们所有的端点都具有“text/plain”的内容类型,因此文本不会被引号包围。
给定这个基本控制器:
[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 标头application/json, text/plain, */*
to application/json, text/plain;q=0.9, */*;q=0.8
但它仍然会返回文本。仅当我们将其设置为application/json
最终会返回json吗?但是,当直接从浏览器窗口点击它时,这并没有帮助,它再次将其返回为“文本/纯文本”。
我们还发现还可以把[Produces("application/json")]
在控制器方法上,这也可以工作。
但考虑到 99% 的端点应该返回 JSON,而几乎没有返回文本或 xml,是否有办法将字符串响应的激进默认值更改为application/json
像 ASP.NET 那样应用程序范围广泛吗?