自訂 Slug 轉換格式

在 ASP.NET Core 上,預設的 Request URL 是 https://localhost:<port>/purchaseorders 的格式,此範例說明如何轉換為 https://localhost:<port>/purchase-orders

範例

  1. 建立 ASP.NET Core Web API (.NET 8) 專案

  2. 新增 API Controller

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    using Microsoft.AspNetCore.Mvc;

    namespace Purchasing.Api.Controllers
    {
    [Route("[controller]")]
    [ApiController]
    public class PurchaseOrdersController : ControllerBase
    {
    [HttpGet]
    public async Task<IActionResult> ListPurchaseOrdersAsync()
    {
    // ...
    }
    }
    }
  3. 新增 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
    18
    using 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();
    }
    }
    }
  4. 配置 RouteTokenTransformerConvention

    Program.cs 新增下列程式碼:

    1
    2
    3
    4
    5
    builder.Services.AddControllers(options =>
    {
    options.Conventions.Add(new RouteTokenTransformerConvention(
    new SlugifyParameterTransformer()));
    });

References