Web API Routing

Web API Routing:

Ở bài phần trước , chúng ta đã hoc về Web API có thể được cấu hình trong lớp WebApiConfig.Bay giờ chúng ta sẽ tìm hiểu về cách để cấu hình Web API routes.
Web API routing tương tự như ASP.NET MVC Routing. Nó dùng định tuyến các yêu cầu HTTP gửi đến cho(từ đó gọi những phương thức cụ thể trong Controller để xử lý) phương thức cụ thể trên Web API Controller.
Web API hỗ trợ hai loại routing sau:
  1. Convention-based Routing
  2. Attribute Routing

Convention-based Routing:

Trong Convention-baed Routing , Web API sử dụng mẫu route để xác định xem controller và phương thức nào sẽ được gọi và thực thi. Có ít nhất một mẫu route được thêm vào table để xử lý những yêu cầu HTTP khác nhau.
Khi chúng ta tạo dự án Web API bằng cách sử dụng mẫu dự án WebAPI mà visual đã tạo sẵn . Trong thư mục App_Start , class WebApiConfig tự thêm vào route mặc định như hiển thị bên dưới.
Ví dụ : WebApiConfig với Route mặc định
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable attribute routing
        config.MapHttpAttributeRoutes();
        
        // Add default route using convention-based routing
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Trong phương thức WebApiConfig.Register() trên. config.MapHttpAttributeRoutes() cho phép cấu hình attribute routing mà chúng ta sẽ tìm hiểu cuối bài này. config.Routes là một bảng route hay nói cách khác là một collection(tập hợp) có kiểu HttpRouteCollection. Route "DefaultApi" được thêm vào bảng(collection) bằng cách sử dụng phương thức mở rộng MapHttpRoute(). Phương thức mở rộng MapHttpRoute() tạo một thể hiển của IHttpRoute và thêm đối tượng kiểu IHttpRoute này vào Collection HttpRouteCollection trên. Tuy nhiên chúng ta có thểm tạo một route mới và thêm nó vào collection này bằng thủ công như sau.
Ví dụ: Add Default Route

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        
        // define route
        IHttpRoute defaultRoute = config.Routes.CreateRoute("api/{controller}/{id}", 
                                            new { id = RouteParameter.Optional }, null);
            
        // Add route
        config.Routes.Add("DefaultApi", defaultRoute);

    }
}

Bảng sau đây liệt kê các tham số của phương thức MapHttpRoute().
Tham sốMô tả
nameTên của route
routeTemplateMẫu URL của route
defaultsAn object parameter that includes default route values
constraintsRegex expression to specify characteristic of route values
handlerThe handler to which the request will be dispatched.
Bay giờ , hãy xem cách Web API xử lý một yêu cầu http đến và gửi phản hồi về.
Sau đây là một yêu cầu HTTP GET mẫu.
Sample HTTP GET Request
GET http://localhost:1234/api/values/ HTTP/1.1
User-Agent: Fiddler
Host: localhost: 60464
Content-Type: application/json
Xem xét route DefaultApi được cấu hình trong lớp WebApiConfig , yêu cầu trên sẽ thực thi phương thức Get() của ValuesController bởi vì phương thức HTTP là Get và URL là "http://localhost:1234/api/values" khớp voí mẫu route là/api/{controller}/{id} trong đó id được chỉ định là thông số truy chọn nếu id không có trong url thì {id} sẽ bị bỏ qua.
If Web API framework does not find matched routes for an incoming request then it will send 404 error response.
The following figure illustrates Web API Routing.


Web API Routing
Web API Routing

The following table displays which action method and controller will be executed on different incoming requests.
Request URLRequest HTTP MethodAction methodController
http://localhost:1234/api/courseGETGet()CourseController
http://localhost:1234/api/productPOSTPost()ProductController
http://localhost:1234/api/teacherPUTPut()TeacherController
Note:Web API also supports routing same as ASP.NET MVC by including action method name in the URL.

Cấu hình nhiều route:

 Chúng ta cấu hình một route đơn giản như sau. Tuy nhiên ,bạn có thể cấu hình nhiều route trong một Web API bằng cách sử dụng đối tượng HttpConfiguration. Ví dụ sau sẽ mô tả cấu hình nhiều route.
Example: Multiple Routes

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
    
        // school route
        config.Routes.MapHttpRoute(
            name: "School",
            routeTemplate: "api/myschool/{id}",
            defaults: new { controller="school", id = RouteParameter.Optional }
            constraints: new { id ="/d+" }
        );

        // default route
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Trong ví dụ trên , Route School được cấu hình trước route DefautApi. Vì vậy bất kỳ yêu cầu nào đến sẽ được so khướp với route School đầu tiên và nếu yêu cầu không khớp với nó thì tiếp tục sẽ được so khớp với route DefaultAPi. Ví dụ url http://localhost:1234/api/myschool được so khớp với Route School , do đó nó sẽ được xử lý bởi SchoolController.
Note:The reason to use api in the route template is just to avoid confusion between MVC controller and Web API controller. You can use any pattern based on your app architecture.
Visit asp.net to learn about routing in detail.

Attribute Routing:

Attribute routing được hỗ trợ trong Web API 2. Cái tên đã nói lên tất cả , attribute routing sử dụng thuộc tính [Route()] để định nghĩa routes. Attribute route có thể được áp dụng ở bất kỳ controller hay action method nào.
Để mà sử dụng attribute routing với Web API , chúng ta phải cấp quyền sử dụng bằng cách gọi phương thức config.MapHttpAttributeRoutes()
Xem xét vị dụ sau về attribute routing.
Example: Attribute Routing

public class StudentController : ApiController
{
    [Route("api/student/names")]
    public IEnumerable<string> Get()
    {
        return new string[] { "student1", "student2" };
    }
}

Ở ví dụ trên , Route attribute định nghĩa route mới "api/student/names" sẽ được xử lý bởi phương thức Get() của controller StudentController. Dó đó , yêu cầu HTTP Get http://localhost:1234/api/student/names sẽ trả về danh sách tên học sinh.
Visit asp.net to learn about attribute routing in detail.

Nhận xét

Đăng nhận xét

Bài đăng phổ biến từ blog này

Web API : Parameter Binding

Action Method Return Type