Nguon: Microsoft Learn · .NET 8.0

Kiểm thử Web API với HttpRepl

Nguồn: Test web APIs with the HttpRepl

HTTP Read-Eval-Print Loop (REPL) là:

Các HTTP verb (động từ HTTP) được hỗ trợ:

Điều kiện tiên quyết

Cài đặt

Để cài đặt HttpRepl, chạy lệnh sau:

dotnetcli
dotnet tool install -g Microsoft.dotnet-httprepl

Một .NET Global Tool được cài đặt từ gói NuGet Microsoft.dotnet-httprepl.

Lưu ý: Theo mặc định, kiến trúc của các tệp nhị phân .NET được cài đặt đại diện cho kiến trúc hệ điều hành đang chạy. Để chỉ định kiến trúc khác, xem cách sử dụng lệnh dotnet tool install với tùy chọn --arch.

Trên macOS, cập nhật path:

bash
export PATH="$HOME/.dotnet/tools:$PATH"

Sử dụng

Sau khi cài đặt thành công, chạy lệnh sau để khởi động HttpRepl:

console
httprepl

Để xem các lệnh HttpRepl có sẵn, chạy một trong các lệnh sau:

console
httprepl -h
console
httprepl --help

Output sau được hiển thị:

console
Usage:
  httprepl [<BASE_ADDRESS>] [options]

Arguments:
  <BASE_ADDRESS> - The initial base address for the REPL.

Options:
  -h|--help - Show help information.

Once the REPL starts, these commands are valid:

Setup Commands:
Use these commands to configure the tool for your API server

connect        Configures the directory structure and base address of the api server
set header     Sets or clears a header for all requests. e.g. `set header content-type application/json`

HTTP Commands:
Use these commands to execute requests against your application.

GET            get - Issues a GET request
POST           post - Issues a POST request
PUT            put - Issues a PUT request
DELETE         delete - Issues a DELETE request
PATCH          patch - Issues a PATCH request
HEAD           head - Issues a HEAD request
OPTIONS        options - Issues a OPTIONS request

Navigation Commands:
The REPL allows you to navigate your URL space and focus on specific APIs that you are working on.

ls             Show all endpoints for the current path
cd             Append the given directory to the currently selected path, or move up a path when using `cd ..`

Shell Commands:
Use these commands to interact with the REPL shell.

clear          Removes all text from the shell
echo [on/off]  Turns request echoing on or off, show the request that was made when using request commands
exit           Exit the shell

REPL Customization Commands:
Use these commands to customize the REPL behavior.

pref [get/set] Allows viewing or changing preferences, e.g. 'pref set editor.command.default 'C:\\Program Files\\Microsoft VS Code\\Code.exe'`
run            Runs the script at the given path. A script is a set of commands that can be typed with one command per line
ui             Displays the Swagger UI page, if available, in the default browser

Use `help <COMMAND>` for more detail on an individual command. e.g. `help get`.
For detailed tool info, see https://aka.ms/http-repl-doc.

HttpRepl cung cấp tính năng tự động hoàn thành lệnh. Nhấn phím Tab để lặp qua danh sách các lệnh khớp với các ký tự hoặc API endpoint bạn đã gõ.

Kết nối với web API

Kết nối với web API bằng cách chạy lệnh sau:

console
httprepl <ROOT URI>

<ROOT URI> là URI cơ sở (base URI) của web API. Ví dụ:

console
httprepl https://localhost:5001

Ngoài ra, chạy lệnh sau bất kỳ lúc nào trong khi HttpRepl đang chạy:

console
connect <ROOT URI>

Ví dụ:

console
(Disconnected)> connect https://localhost:5001

Chỉ định thủ công mô tả OpenAPI cho web API

Lệnh connect ở trên sẽ cố gắng tìm mô tả OpenAPI tự động. Nếu không thể, bạn có thể chỉ định URI của mô tả OpenAPI cho web API bằng tùy chọn --openapi:

console
connect <ROOT URI> --openapi <OPENAPI DESCRIPTION ADDRESS>

Ví dụ:

console
(Disconnected)> connect https://localhost:5001 --openapi /swagger/v1/swagger.json

Bật output verbose để biết chi tiết về tìm kiếm mô tả OpenAPI

Chỉ định tùy chọn --verbose với lệnh connect để có thêm chi tiết khi công cụ tìm kiếm, phân tích cú pháp và xác thực mô tả OpenAPI:

console
(Disconnected)> connect https://localhost:5001 --verbose
Checking https://localhost:5001/swagger.json... 404 NotFound
Checking https://localhost:5001/swagger/v1/swagger.json... 404 NotFound
Checking https://localhost:5001/openapi.json... Found
Parsing... Successful (with warnings)
The field 'info' in 'document' object is REQUIRED [#/info]
The field 'paths' in 'document' object is REQUIRED [#/paths]

Điều hướng web API

Xem các endpoint có sẵn

Để liệt kê các endpoint (controller) khác nhau tại path hiện tại của địa chỉ web API, chạy lệnh ls hoặc dir:

console
https://localhost:5001/> ls

Output được hiển thị theo định dạng:

console
.        []
Fruits   [get|post]
People   [get|post]

https://localhost:5001/>

Output trên cho thấy có hai controller: FruitsPeople. Cả hai đều hỗ trợ HTTP GET và POST không tham số.

Điều hướng vào một controller cụ thể để xem thêm chi tiết. Ví dụ, lệnh sau cho thấy controller Fruits cũng hỗ trợ HTTP GET, PUT và DELETE với tham số id trong route:

console
https://localhost:5001/fruits> ls
.      [get|post]
..     []
{id}   [get|put|delete]

https://localhost:5001/fruits>

Ngoài ra, chạy lệnh ui để mở trang Swagger UI của web API trong trình duyệt:

console
https://localhost:5001/> ui

Điều hướng đến endpoint

Để điều hướng đến endpoint khác trên web API, chạy lệnh cd:

console
https://localhost:5001/> cd people

Path theo sau lệnh cd không phân biệt hoa/thường:

console
/people    [get|post]

https://localhost:5001/people>

Tùy chỉnh HttpRepl

Màu sắc mặc định của HttpRepl có thể được tùy chỉnh. Ngoài ra, trình soạn thảo văn bản mặc định có thể được định nghĩa. Các tùy chọn của HttpRepl được lưu trong phiên hiện tại và được áp dụng trong các phiên tương lai. Sau khi thay đổi, tùy chọn được lưu trong file sau:

File .httpreplprefs được tải khi khởi động và không được theo dõi thay đổi khi chạy. Các sửa đổi thủ công chỉ có hiệu lực sau khi khởi động lại công cụ.

Xem cài đặt

Để xem các cài đặt có sẵn, chạy lệnh pref get:

console
https://localhost:5001/> pref get

Lệnh trên hiển thị các cặp key-value (khóa-giá trị) có sẵn:

console
colors.json=Green
colors.json.arrayBrace=BoldCyan
colors.json.comma=BoldYellow
colors.json.name=BoldMagenta
colors.json.nameSeparator=BoldWhite
colors.json.objectBrace=Cyan
colors.protocol=BoldGreen
colors.status=BoldYellow

Đặt tùy chọn màu sắc

Tô màu response hiện chỉ được hỗ trợ cho JSON. Để tùy chỉnh màu sắc mặc định, xác định key tương ứng với màu cần thay đổi. Ví dụ, thay đổi giá trị key colors.json từ Green thành White:

console
https://localhost:5001/people> pref set colors.json White

Chỉ các màu được phép mới có thể được sử dụng.

Khi các key màu cụ thể không được đặt, các key tổng quát hơn sẽ được xem xét theo thứ tự fallback:

Đặt kích thước thụt đầu dòng

Tùy chỉnh kích thước thụt đầu dòng response hiện chỉ được hỗ trợ cho JSON. Kích thước mặc định là hai dấu cách. Để thay đổi thành bốn dấu cách:

console
pref set formatting.json.indentSize 4

Đặt trình soạn thảo văn bản mặc định

Theo mặc định, HttpRepl không có trình soạn thảo văn bản nào được cấu hình. Để kiểm thử các phương thức web API yêu cầu body HTTP request, cần đặt trình soạn thảo văn bản mặc định. Chạy lệnh sau để đặt trình soạn thảo ưa thích:

console
pref set editor.command.default "<EXECUTABLE>"

Ví dụ, đặt Visual Studio Code làm trình soạn thảo mặc định:

Để khởi chạy trình soạn thảo với các đối số CLI cụ thể, đặt key editor.command.default.arguments. Ví dụ, để luôn mở Visual Studio Code trong phiên mới với extension bị tắt:

console
pref set editor.command.default.arguments "--disable-extensions --new-window"

Mẹo: Nếu trình soạn thảo mặc định là Visual Studio Code, bạn thường muốn truyền đối số -w hoặc --wait để buộc Visual Studio Code chờ cho đến khi bạn đóng file trước khi trả về.

Đặt đường dẫn tìm kiếm mô tả OpenAPI

Theo mặc định, HttpRepl có một tập hợp các đường dẫn tương đối để tìm mô tả OpenAPI khi thực thi lệnh connect không có tùy chọn --openapi. Các đường dẫn tương đối mặc định là:

Để sử dụng tập hợp đường dẫn tìm kiếm khác, đặt tùy chọn swagger.searchPaths. Giá trị phải là danh sách đường dẫn tương đối phân cách bằng dấu |:

console
pref set swagger.searchPaths "swagger/v2/swagger.json|swagger/v3/swagger.json"

Để thêm một hoặc nhiều đường dẫn vào danh sách mặc định:

console
pref set swagger.addToSearchPaths "openapi/v2/openapi.json|openapi/v3/openapi.json"

Để xóa một hoặc nhiều đường dẫn khỏi danh sách mặc định:

console
pref set swagger.removeFromSearchPaths "swagger.json|/swagger.json"

Kiểm thử HTTP GET request

Cú pháp

console
get <PARAMETER> [-F|--no-formatting] [-h|--header] [--response:body] [--response:headers] [-s|--streaming]

Ví dụ

Để thực hiện HTTP GET request:

  1. Chạy lệnh get trên endpoint hỗ trợ nó:

``console https://localhost:5001/people> get ``

Output:

```console HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Date: Fri, 21 Jun 2019 03:38:45 GMT Server: Kestrel Transfer-Encoding: chunked

[ { "id": 1, "name": "Scott Hunter" }, { "id": 2, "name": "Scott Hanselman" }, { "id": 3, "name": "Scott Guthrie" } ]

https://localhost:5001/people> ```

  1. Truy xuất một bản ghi cụ thể bằng cách truyền tham số:

``console https://localhost:5001/people> get 2 ``

Kiểm thử HTTP POST request

Cú pháp

console
post <PARAMETER> [-c|--content] [-f|--file] [-h|--header] [--no-body] [-F|--no-formatting] [--response] [--response:body] [--response:headers] [-s|--streaming]

Ví dụ

Để thực hiện HTTP POST request:

  1. Chạy lệnh post trên endpoint hỗ trợ nó:

``console https://localhost:5001/people> post -h Content-Type=application/json ``

Lệnh trên đặt header Content-Type để chỉ định loại phương tiện của body là JSON. Trình soạn thảo văn bản mặc định mở file .tmp với template JSON đại diện cho body HTTP request:

``json { "id": 0, "name": "" } ``

  1. Sửa đổi template JSON để đáp ứng yêu cầu xác thực model:

``json { "id": 0, "name": "Scott Addie" } ``

  1. Lưu file .tmp và đóng trình soạn thảo. Output sau hiện ra:

```console HTTP/1.1 201 Created Content-Type: application/json; charset=utf-8 Date: Thu, 27 Jun 2019 21:24:18 GMT Location: https://localhost:5001/people/4 Server: Kestrel Transfer-Encoding: chunked

{ "id": 4, "name": "Scott Addie" }

https://localhost:5001/people> ```

Kiểm thử HTTP PUT request

Cú pháp

console
put <PARAMETER> [-c|--content] [-f|--file] [-h|--header] [--no-body] [-F|--no-formatting] [--response] [--response:body] [--response:headers] [-s|--streaming]

Ví dụ

Để thực hiện HTTP PUT request:

  1. Tùy chọn: chạy lệnh get để xem dữ liệu trước khi sửa đổi.
  2. Chạy lệnh put trên endpoint hỗ trợ nó, ví dụ: put 2 -h Content-Type=application/json
  3. Sửa đổi template JSON và lưu file.

Kiểm thử HTTP DELETE request

Cú pháp

console
delete <PARAMETER> [-F|--no-formatting] [-h|--header] [--response] [--response:body] [--response:headers] [-s|--streaming]

Ví dụ

Để thực hiện HTTP DELETE request:

console
https://localhost:5001/fruits> delete 2

Output:

console
HTTP/1.1 204 No Content
Date: Fri, 28 Jun 2019 17:36:42 GMT
Server: Kestrel

Đặt HTTP request header

Để đặt HTTP request header, sử dụng một trong các cách sau:

``console https://localhost:5001/people> post -h Content-Type=application/json ``

``console https://localhost:5001/people> set header Content-Type application/json ``

Khi đặt header trước khi gửi, header đó vẫn được đặt trong suốt phiên shell. Để xóa header, cung cấp giá trị rỗng:

``console https://localhost:5001/people> set header Content-Type ``

Kiểm thử endpoint bảo mật

HttpRepl hỗ trợ kiểm thử các endpoint bảo mật theo các cách sau:

Thông tin xác thực mặc định

Để truyền thông tin xác thực mặc định của người dùng đang đăng nhập, đặt tùy chọn httpClient.useDefaultCredentials thành true:

console
pref set httpClient.useDefaultCredentials true

HTTP request header

Các ví dụ về scheme xác thực và ủy quyền được hỗ trợ bao gồm:

Ví dụ, gửi bearer token đến endpoint:

console
set header Authorization "bearer <TOKEN VALUE>"

Để truy cập endpoint được host trên Azure hoặc sử dụng Azure REST API, cần có bearer token. Sử dụng Azure CLI để lấy bearer token:

  1. Đăng nhập Azure: az login
  2. Lấy subscription ID: az account show --query id
  3. Đặt subscription: az account set --subscription "<SUBSCRIPTION ID>"
  4. Lấy bearer token: az account get-access-token --query accessToken
  5. Kết nối với Azure REST API: httprepl https://management.azure.com
  6. Đặt header Authorization: set header Authorization "bearer <ACCESS TOKEN>"

Bật/tắt hiển thị HTTP request

Bật hiển thị request

Xem HTTP request đang được gửi bằng cách chạy lệnh echo on:

console
https://localhost:5001/people> echo on
Request echoing is on

Tắt hiển thị request

Ẩn hiển thị HTTP request đang được gửi:

console
https://localhost:5001/people> echo off
Request echoing is off

Chạy script

Nếu bạn thường xuyên thực thi cùng tập hợp lệnh HttpRepl, hãy lưu chúng vào file văn bản. Các lệnh trong file có cùng dạng với các lệnh được thực thi thủ công. Chúng có thể được thực thi theo lô bằng lệnh run:

  1. Tạo file văn bản chứa tập hợp các lệnh. Ví dụ, file people-script.txt:

``text set base https://localhost:5001 ls cd People ls get 1 ``

  1. Thực thi lệnh run, truyền đường dẫn file:

``console https://localhost:5001/> run C:\http-repl-scripts\people-script.txt ``

Xóa output

Để xóa tất cả output đã được ghi vào command shell, chạy lệnh clear hoặc cls:

console
https://localhost:5001/> clear