[c#] オレオレblogのRouter

前回まで

MVCのFW使った場合にWordPressのpost_nameをルートパスにして云々でボケーっと考えていたのだが、MSDN見ながら実装してたらボケーッとしてた時間が無駄だったっていうオチ。

ASP.NET Core のルーティング | Microsoft Docs

ASP.net 空のプロジェクトから

IndexとCategoryのControllerを追加。Startup.csでRouter定義。超楽ちんだった。

Startup.cs

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseEndpoints(endpoints => {
                /*endpoints.MapControllerRoute(name: "default",pattern:"{controller=Index}/{action=Index}/{id?}");*/
                endpoints.MapControllerRoute(
                    name: "index",
                    pattern: "{args?}",
                    defaults: new { controller = "Index", action = "Index", });
                endpoints.MapControllerRoute(
                    name: "category",
                    pattern: "/category/{code?}",
                    defaults: new { controller = "Category", action = "Index", });
            });
        }

Controllers/IndexController.cs

    public class IndexController : Controller {
        public IActionResult Index(string args) {
            ViewBag.Code = args ?? string.Empty;
            return View();
        }
    }

Controllers/CategoryController.cs

    public class CategoryController : Controller {
        public IActionResult Index(string code) {
            ViewBag.Code = code ?? string.Empty;
            return View();
        }
    }

Indexのargsがnullだった場合はトップページ描画、エントリーの識別子が入ってたらDBからゲットして描画。なければ404にでも飛ばす。これに /page/{number}/ とか /category/page/{number}/ とかページャー周りをRouterに追加するだけじゃん。カテゴリだけでコメントとかいらないので。次はgo(gin)を見てみてどっちにするか決めようと思う。というかC#さんのASP.netが優秀すぎて、こっちにした場合frontendはマジやること無いな!