自訂 Slug 轉換格式
在 ASP.NET Core 上,預設的 Request URL 是 https://localhost:<port>/purchaseorders
的格式,此範例說明如何轉換為 https://localhost:<port>/purchase-orders
。
範例
建立
ASP.NET Core Web API (.NET 8)
專案新增
API Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15using Microsoft.AspNetCore.Mvc;
namespace Purchasing.Api.Controllers
{
[ ]
[ ]
public class PurchaseOrdersController : ControllerBase
{
[ ]
public async Task<IActionResult> ListPurchaseOrdersAsync()
{
// ...
}
}
}新增
SlugifyParameterTransformer
Class實作
IOutboundParameterTransformer
Interface 的TransformOutbound
Method,用Regular Expression
進行轉換。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18using System.Text.RegularExpressions;
namespace Purchasing.Api.Routing
{
public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
public string? TransformOutbound(object? value)
{
if (value == null) { return null; }
return Regex.Replace(value.ToString()!,
"([a-z])([A-Z])",
"$1-$2",
RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(100)).ToLowerInvariant();
}
}
}配置
RouteTokenTransformerConvention
在
Program.cs
新增下列程式碼:1
2
3
4
5builder.Services.AddControllers(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(
new SlugifyParameterTransformer()));
});