为最小 API 创建小写 URL
Make lowercase URLs for minimal API
说,我有以下最小值 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();
当我传递不存在的 id
时,我得到以下 JSON:
{
"requested_Id": 15,
"message": "Customer not found."
}
问题是requested_Id
中的字母I
不是小写的,尽管我在Configure<RouteOptions>
中配置了它。但是当我开始使用成熟的控制器时,我正确地得到 requested_id
。如何使用 MapGet
实现相同的效果?
配置默认 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();
}
说,我有以下最小值 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();
当我传递不存在的 id
时,我得到以下 JSON:
{
"requested_Id": 15,
"message": "Customer not found."
}
问题是requested_Id
中的字母I
不是小写的,尽管我在Configure<RouteOptions>
中配置了它。但是当我开始使用成熟的控制器时,我正确地得到 requested_id
。如何使用 MapGet
实现相同的效果?
配置默认 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();
}