Routing in ASP.NET Core 2.1

Cầu hình Route(Định tuyến đường đi cho một URL). Đa phần chúng ta xây dựng trong ASP.NET ta cần phải cấu hình tùy biến Route sao cho đường dẫn nó đẹp cho SEO
Nay mình sẽ đi qua các bước chia sẻ nhỏ để mọi người có thể hình dung và cấu hình nó tuy biến, về cơ bản Route ASP.NET là gì? thì trên mạng cũng khá là nhiều rồi, nên mọi người có thể xem thêm
Trong chia sẻ này mình tạo một file ProductController.cs trong thư mục Controllers, Mình sẽ tạo mấy cái Action , để hồi mình cấu hình Route gọi đến Action

public class ProductController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

       
        public ActionResult Details(string slug)
        {
            ViewBag.slug = slug;
            return View();
        }

      
        public ActionResult Information(string slug)
        {
            ViewBag.slug = slug;
            return View();
        }

      
        public ActionResult Downloads(int? id,string slug)
        {
            ViewBag.id = id;
            ViewBag.slug = slug;
            return View();
        }
}

Trong  Startup.cs tại cần cấu hình route trong đây, mình sẽ dùng regex để cấu hình Route, mình rất thích sài Regex bạn có thể xem thêm tại đây
https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference

Route configuration in Startup file

 var regexId = @"^[\d]{1,9}$";
                var regexSlug = @"^[0-9]{1,7}\-[a-z0-9\-]{3,50}$";
                var regexDate = @"^[\d]{2}\-[\d]{2}\-[\d]{4}$";

                // url: downloads/1213/12-san-pham
                routes.MapRoute(
                    name: "product_router3",
                    template: "downloads/{id}/{*slug}",
                    constraints: new { id = regexId, slug = regexSlug },
                    defaults: new { controller = "Product", action = "Downloads" }
                );

                // url: san-pham/12-san-pham
                routes.MapRoute(
                    name: "product_router2",
                    template: "san-pham/{*slug}",
                    constraints: new {slug = regexSlug },
                    defaults: new { controller = "Product", action = "Information" }
                );

                // url: tin-tuc/05-06-2020/12-san-pham
                routes.MapRoute(
                    name: "product_router1",
                    template: "tin-tuc/{date}/{*slug}",
                    constraints: new { slug = regexSlug,  date= regexDate },
                    defaults: new { controller = "Product", action = "Details" }
                );
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

Thông thương ta thường thích đường dẫn URL như sau: /tin-tuc/bai-viet-aspnet hay là /bai-viet-aspnet , bạn có thể làm được nó nhé, 
Bạn tìm hiểu thêm về Regex để có thể cấu hình Route một cách linh động hơn
+ ^[\d]{1,9} :  Nhập ký tự số, ít nhất chiều dài 1 ký tự, tối đa là 9
+ [a-z0-9\-] :  Chấp nhận ký tự từ a->z, 0->9
+ name: Đặt một name để phân biệt các route khác
+ template: Bạn có thể cấu hình template đường dẫn mà bạn muốn
+ constraints: dùng để cấu hình các tham số ràng buộc trong đường dẫn URL
Nói chung về Regex nó rất là phức tạp, bạn cần phải chạy thử nghiệm nó mới dễ hình dung ra, dù ta đã biết lý thuyết đi chẳng nửa, nhưng ta phải thử nó như thế nào!

Route configuration in Controller file

Ok, ban đầu mình có cấu hình Route trong file Startup.cs giờ bạn xóa bỏ hết chỉ chừa lại file mặt định của Route 

//startup.cs
routes.MapRoute(
   name: "default",
   template: "{controller=Shop}/{action=Index}/{id?}");

+ ShopController.cs
       
        [Route("")]
        [Route("shopit")]
        [Route("shopit/trang-chu")]
        public ActionResult Index()
        {
            return View();
        }

Trong cái Action Index(), mình có cấu hình các Route như trên , nó điều gọi Action Index()
[Route("")] : khi bạn rõ URL: https://localhsot:port của các bạn
[Route("shopit")] : Sửa URL: https://localhsot:port/shopit
[Route("shopit/trang-chu")] : Sửa URL: https://localhsot:port/shopit/trang-chu
Bạn có thể cấu hình Route kiểu này trong file Controller của các bạn.
Ok tiếp theo ta cấu hình Action Details với URL: /shopit/12/san-pham-khuyen-mai-2019

 [Route(@"/shopit/{id:int}/{article:regex(^[[a-z0-9\-]]{{2,50}}$)}")]
        public ActionResult Details(int id,string article)
        {
            return View();
        }

{id:int}:chỉ lấy giá trị kiểu int
{article:regex(^[[a-z0-9\-]]{{2,50}}$)} : chỉ nhận giá trị từ a-z,0-9, ít nhất 2 ký tự, tối đa 50 ký tự

Nếu bạn dùng RESTful API , ta có thể cấu hình trong file Controller và gọi URL:/api/shop, /api/shop/2 

Route("api/[controller]")]
    public class ShopController : Controller
    {
        [HttpGet("")]
        public JsonResult GetAllShop()
        {
            
            return Json("data");
        }
        [HttpGet("{id:int}")]
        public JsonResult GetShop(int id)
        {
            return Json(id);
        }
        [HttpGet(@"{id:int}/{slug:regex(^[[a-z\-]]{{2,50}}$)}")]
        public JsonResult GetShopContent(int id,string slug)
        {
            
            return Json(id+"-"+slug);
        }

        // POST: Shop/Create
        [HttpPost("")]
        public JsonResult CreateShop([FromBody] Shop _shop)
        {
            return Json(_shop);
        }

        // POST: Shop/Edit
        [HttpPost("{id:int}")]
        public JsonResult EditShop(int id,[FromBody] Shop _shop)
        {
            var idShop = 123;
            _shop.idShop = idShop;
            return Json(_shop);
        } 

Còn rất là nhiều Regex các bạn có thể tìm hiểu thêm nhé, 

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)