c# - 如何在 ASP.NET Core 7 中以 JSON 形式返回纯字符串

标签 c# asp.net asp.net-core

正在从 .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/

相关文章:

C# 遵守从​​ SQL 服务器中提取的字符串中的换行符

c# - 毛玻璃窗上的非客户绘画

asp.net - ValidationSummary 样式在 Post asp.net 的 IE 6 中不显示

c# - 使用 appsettings.Production.json 中的数组设置覆盖 appsettings.json 中的数组设置

linux - VS 代码 + 开发(Linux) + 目标(.net Framework) + 主机(Windows)

amazon-web-services - IIS 上的 appConcurrentRequest 超出限制

c# - 是否可以传递服务过滤器参数?

c# - 将 System.Web.Mail 功能移植到 System.Net.Mail

c# - 加载后面的代码后加载javascript代码

asp.net - Wordpress 喜欢 asp.net 页面中的短代码吗?