0

Say, I have the following minimal 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();

When I pass non-existing id, I get the following JSON:

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

The problem is that letter I in requested_Id is not lowercase, although I configured it in Configure<RouteOptions>. But when I start using fully-fledged controller, then I correctly get requested_id. How do I achieve the same with MapGet?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
JohnyL
  • 6,894
  • 3
  • 22
  • 41

2 Answers2

2

Configure the default Json options (Note the using for the correct namespace)

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();    
}
Mister Magoo
  • 7,452
  • 1
  • 20
  • 35
0

You can use below line fo code to convert all words in URL as lowercase

services.AddRouting(options => options.LowercaseUrls = true);