3

使用 ASP.NET Core 3 和 System.Text.Json,您可以通过添加返回格式精美的 JSON

services.AddControllers().AddJsonOptions(
options => options.JsonSerializerOptions.WriteIndented = true);

到您的 Startup.cs ...

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddApiVersioning(o =>
    {
        o.AssumeDefaultVersionWhenUnspecified = true;
        o.DefaultApiVersion = new ApiVersion(1, 0);
    });

    services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
}

...但这意味着,它可以为所有端点全局打印所有 JSON 输出。

有没有办法在端点级别决定漂亮与否,例如通过查询字符串“pretty=true”?:

https://localhost:5001/api/v1/persons/1231221.json?pretty=true

在你的 Controllers/PersonController.cs 你可以做......

[HttpGet]
[Route("/api/v{version:apiVersion}/[controller]/{id}.json")]
public IActionResult PersonAsJson([FromRoute] int id, [FromQuery] bool pretty = false)
{
    var person = new Person(id)

    // ...

    if (pretty)
    {
        Response.Headers.Add("Content-Type", "text/plain");

        return Ok(JsonSerializer.Serialize(
            person,
            new JsonSerializerOptions { WriteIndented = true }));
    }

    // non pretty output if there's no
    // services.AddControllers().AddJsonOptions(
    //    options => options.JsonSerializerOptions.WriteIndented = true);
    // in Startup.cs

    Response.Headers.Add("Content-Type", "application/json");

    return Ok(person);
}

...但这显然会为格式精美的 JSON 返回错误的 Content-Type。

我还看不到的任何解决方案?

4

2 回答 2

1

由于您的两个回答都必须满足Content-Type: application/json,我会这样做:

[HttpGet]
[Route("/api/v{version:apiVersion}/[controller]/{id}.json")]
public IActionResult PersonAsJson([FromRoute] int id, [FromQuery] bool pretty = false)
{
    var person = new Person(id)

    // ...

    Response.Headers.Add("Content-Type", "application/json");

    if (pretty)
    {
        return Ok(JsonSerializer.Serialize(
            person,
            new JsonSerializerOptions { WriteIndented = true }));
    }

    // non pretty output if there's no
    // services.AddControllers().AddJsonOptions(
    //    options => options.JsonSerializerOptions.WriteIndented = true);
    // in Startup.cs

    return Ok(person);
}

无需设置标题两次。

于 2019-10-18T11:06:29.470 回答
0

它可以是内容的类型:

    Response.Headers.Add("Content-Type", "application/json;");

会像:

if (pretty)
{
    Response.Headers.Add("Content-Type", "application/json;");

    return Ok(JsonSerializer.Serialize(
        person,
        new JsonSerializerOptions { WriteIndented = true }));
}
于 2019-10-18T11:02:56.840 回答