TOC

This article is currently in the process of being translated into Vietnamese (~41% done).

Routing:

The anatomy of an MVC Route

Trong bài giảng, chúng ta đã nói về routing cơ bản nhờ routing mặc định. Tuy nhiên, để hiểu làm sao định nghĩa được đường dẫn, bạn cần tìm hiểu thêm để tạo thêm đường dẫn khác mặc định.

Phần quan trọng nhất của định tuyến là làm sao ánh xạ từ URL sang phương thức của Controller. Ta cần biết đường dẫn URLtên của Controller cùng phương thức. Hệ thống có thể xác định luật (bạn cũng có thể phải nhớ các luật nếu có nhiều), nên chúng ta cần đặt tên cho luật.

With that in mind, let's try creating a very basic rule. As mentioned, rules can be defined in several ways and places, but we'll start out doing it in the Startup.cs file, inside the Configure() method:

app.UseMvc(routes =>
routes.MapRoute("ProductList", "Products/List/", new { controller = "Products", action = "List" })
);

The call to MapRoute() takes several parameters - in this case, we supply a name for the route (the first parameter), the URL template for the rule (the second parameter), as well as an object of "defaults" (the third parameter), which will direct the rule to the desired Controller and method on that Controller. So, with this in place, we can now call the URL http://localhost/Products/List, and the List() method on the ProductsController will be called.

The Route template

Thú vị nhất là tham số thứ hai về định nghĩa định dạng cho đường dẫn rấtđơn giản, cho phép hỗ trợ những URL phức tạp. Cần định nghĩa controller mặc định với action:

routes.MapRoute("Default", "{controller=Home}/{action=Index}")

Giống đường dẫn cơ bản, vì nó chứa ít nhất hai phần, phần đầu là controller và phần sau là action. Phần thứ ba tùy chọn thường là ID. Có thể định nghĩa ID với cú pháp đặc biệt. Hãy nhìn vào ví dụ:

app.UseMvc(routes =>
routes.MapRoute("Products", "Products/{action=Index}/{id?}", new { controller = "Products" })
);

The template now matches URL's which starts with the word "products". If nothing else is specified, it will default to the Index action/method. On the other hand, if an action is specified in the second part of the URL, it will be used. At the end, we have an optional ID parameter - the fact that it's optional is noted with the use of a question mark. We now support the following URL's:

  • /Products/
  • /Products/List/
  • /Products/Details/32/

The Controller to handle all these scenarios could look like this:

public class ProductsController : Controller
{
public IActionResult Index()
{
    return Content("Product overview");
}

public IActionResult List()
{
    return Content("Product list");
}

public IActionResult Details(int id)
{
return Content("Product details for #" + id);
}
}

Notice especially the Details methods - it has a parameter called "id", which matches the parameter we specified in the route. This means that if you call the Details URL, the ID you append to it will automatically be passed as the id parameter to the Details method!

As you can see, the routing template system is very flexible and allows you to support many different URL variations. There are many more possibilities, which we'll look into later in this tutorial, but hopefully these examples have given you a good idea on just how powerful the routing mechanisms in ASP.NET Core MVC is.

Multiple routes

Chúng ta có thể có hơn một đường dẫn trong ứng dụng. Thực tế, phương pháp chung nhất là có đường dẫn mặc định, nên để đầu tiên. Tại sao? Bởi luật đường dẫn được xử lý từ đầu đến cuối, cho tới khi tìm được đường phù hợp thì dừng lại. Nói cách khác, luật cụ thể nên để trên đầu cho tơi khi ít cụ thể dần.

app.UseMvc(routes =>  
{  
routes.MapRoute("Products", "Products/{action=Index}/{id?}", new { controller = "Products" });  
routes.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");  
});

Nếu không tìm thấy đường dẫn cụ thể vơi Controller/Action thì sẽ trả về Index() trong HomeController.

Summary

By now, you should have a much better idea about how routing works and how to define your own routes. During the next articles, we will look into more available options you have when defining your routes, as well as other ways of using the routing mechanisms of ASP.NET MVC.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!