4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ASP.NET Core Web APIのURLにケバブケースを使いたい

Posted at

やりたいこと

ASP.NET CoreでWeb APIを作成した時は、標準ではURLがPascal Caseになります。

例えば、以下の例では、/SubscriptionManagement/ListAll がURLのパスになります。

public class SubscriptionManagementController : Controller
{
    [HttpGet("[controller]/[action]")]
    public IActionResult ListAll()
    {
        return ControllerContext.MyDisplayRouteInfo();
    }
}

これを/subscription-management/list-all にようなケバブケース(kebab case)にしたい場合があります。

ケバブケースにする方法

公式ページの
ASP.NET Core でのコントローラー アクションへのルーティング の「パラメーター トランスフォーマーを使用してトークンの置換をカスタマイズする」に書かれています。

IOutboundParameterTransformer インターフェースを実装

まず、やることは、IOutboundParameterTransformer インターフェースを実装したクラスを定義します。公式ページのコードそのままです。

using System.Text.RegularExpressions;

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();
    }
}

Program.cs でSlugifyParameterTransformerを追加

そして、Program.cs に以下のようなコードを追加します(.NET 6の場合)。

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews(options =>
{
    options.Conventions.Add(new RouteTokenTransformerConvention(
            new SlugifyParameterTransformer()));
});

これにより、パラメーター トランスフォーマーをアプリケーションのすべての属性ルートに適用します。

.NET 5、.NET Core 3.1の場合は、Startup.csのConfigureServicesメソッドで、以下を追加します。

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews(options =>
    {
        options.Conventions.Add(new RouteTokenTransformerConvention(
                                     new SlugifyParameterTransformer()));
    });

}

これで、ケバブケース(kebab case)になります。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?