0

说,我有以下最小的 API:

var builder = WebApplication.CreateBuilder(args);

// Routing options
builder.Services
  .Configure<RouteOptions>(options =>
  {
    options.LowercaseUrls = true;
    options.LowercaseQueryStrings = true;
  });

await using var app = builder.Build();

// API
app.MapGet("/api/customers/{id:int}", async (VRContext db, int id) =>
  await db.Customers.FindAsync(id) switch
  {
    { } customer => Results.Ok(customer),
    null => Results.NotFound(new { Requested_Id = id, Message = $"Customer not found." })
  });

//app.MapControllers();

await app.RunAsync();

当我通过 non-existingid时,我得到以下 JSON:

{
  "requested_Id": 15,
  "message": "Customer not found."
}

问题是字母Iinrequested_Id不是小写的,虽然我在Configure<RouteOptions>. 但是当我开始使用成熟的控制器时,我正确地得到了requested_id. 我如何达到同样的效果MapGet

4

1 回答 1

1

配置默认的 Json 选项(注意using正确的命名空间)

using Microsoft.AspNetCore.Http.Json;

var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<JsonOptions>(
    options =>
    {
        options.SerializerOptions.PropertyNamingPolicy = new LowerCaseNamingPolicy();
    });

await using var app = builder.Build();

// API
app.MapGet("/api/customers/{id:int}", (int id) =>
        Results.NotFound(new { Requested_Id = id, Message = $"Customer not found." })
        );

await app.RunAsync();
internal class LowerCaseNamingPolicy : JsonNamingPolicy
{
    public override string ConvertName(string name) => name.ToLowerInvariant();    
}
于 2022-01-04T10:47:32.313 回答