Skip to main content

APIRequestContext

该 API 用于 Web API 测试。你可以使用它来触发 API 端点、配置微服务、为 e2e 测试准备环境或服务。

¥This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services, prepare environment or the service to your e2e test.

每个 Playwright 浏览器上下文都有与其关联的 APIRequestContext 实例,该实例与浏览器上下文共享 cookie 存储,并且可以通过 BrowserContext.APIRequestPage.APIRequest 访问。也可以通过调用 ApiRequest.NewContextAsync().手动创建一个新的 APIRequestContext 实例。

¥Each Playwright browser context has associated with it APIRequestContext instance which shares cookie storage with the browser context and can be accessed via BrowserContext.APIRequest or Page.APIRequest. It is also possible to create a new APIRequestContext instance manually by calling ApiRequest.NewContextAsync().

Cookie 管理

¥Cookie management

BrowserContext.APIRequest 返回的 APIRequestContextPage.APIRequest 与相应的 BrowserContext 共享 cookie 存储。每个 API 请求都会有 Cookie 标头,其中填充了浏览器上下文中的值。如果 API 响应包含 Set-Cookie 标头,它将自动更新 BrowserContext cookie,并且从页面触发的请求将获取它们。这意味着,如果你使用此 API 登录,你的 e2e 测试将被登录,反之亦然。

¥APIRequestContext returned by BrowserContext.APIRequest and Page.APIRequest shares cookie storage with the corresponding BrowserContext. Each API request will have Cookie header populated with the values from the browser context. If the API response contains Set-Cookie header it will automatically update BrowserContext cookies and requests made from the page will pick them up. This means that if you log in using this API, your e2e test will be logged in and vice versa.

如果你希望 API 请求不干扰浏览器 cookie,你应该通过调用 ApiRequest.NewContextAsync() 创建一个新的 APIRequestContext。这样的 APIRequestContext 对象将有自己独立的 cookie 存储。

¥If you want API requests to not interfere with the browser cookies you should create a new APIRequestContext by calling ApiRequest.NewContextAsync(). Such APIRequestContext object will have its own isolated cookie storage.


方法

¥Methods

CreateFormData

Added in: v1.23 apiRequestContext.CreateFormData

创建一个新的 FormData 实例,用于在发送 HTTP 请求时提供表单和多部分数据。

¥Creates a new FormData instance which is used for providing form and multipart data when making HTTP requests.

用法

¥Usage

ApiRequestContext.CreateFormData

返回

¥Returns


DeleteAsync

Added in: v1.16 apiRequestContext.DeleteAsync

发送 HTTP(S) DELETE 请求并返回其响应。该方法将从上下文填充请求 cookie,并从响应更新上下文 cookie。该方法将自动遵循重定向。

¥Sends HTTP(S) DELETE request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.

用法

¥Usage

await ApiRequestContext.DeleteAsync(url, options);

参数

¥Arguments

目标网址。

¥Target URL.

  • options ApiRequestContextDeleteOptions?(可选)

    ¥options ApiRequestContextDeleteOptions? (optional)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (optional) Added in: v1.17#

允许设置请求的发布数据。如果 data 参数是一个对象,它将被序列化为 json 字符串,如果没有显式设置,content-type header 将被设置为 application/json。否则,如果未显式设置,content-type 标头将设置为 application/octet-stream

¥Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

  • FailOnStatusCode bool? (optional)#

是否抛出除 2xx 和 3xx 之外的响应代码。默认情况下,为所有状态代码返回响应对象。

¥Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

提供一个对象,该对象将使用 application/x-www-form-urlencoded 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 application/x-www-form-urlencoded

¥Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

允许设置 HTTP 标头。这些标头将应用于获取的请求以及由其发起的任何重定向。

¥Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

  • IgnoreHTTPSErrors bool? (optional)#

发送网络请求时是否忽略 HTTPS 错误。默认为 false

¥Whether to ignore HTTPS errors when sending network requests. Defaults to false.

  • MaxRedirects int? (optional) Added in: v1.26#

自动遵循的请求重定向的最大数量。如果超过数量将会抛出错误。默认为 20。通过 0 不遵循重定向。

¥Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

  • MaxRetries int? (optional) Added in: v1.46#

应重试网络错误的最大次数。当前仅重试 ECONNRESET 错误。不根据 HTTP 响应代码重试。如果超出限制,将引发错误。默认为 0 - 不重试。

¥Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.

  • Multipart FormData? (optional) Added in: v1.17#

提供一个对象,该对象将使用 multipart/form-data 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。

¥Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • ParamsString string? (optional) Added in: v1.47#

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • Timeout [float]? (optional)#

请求超时(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

返回

¥Returns


DisposeAsync

Added in: v1.16 apiRequestContext.DisposeAsync

ApiRequestContext.GetAsync() 和类似方法返回的所有响应都存储在内存中,以便稍后调用 ApiResponse.BodyAsync()。该方法会丢弃其所有资源,调用已处理的 APIRequestContext 上的任何方法都会抛出异常。

¥All responses returned by ApiRequestContext.GetAsync() and similar methods are stored in the memory, so that you can later call ApiResponse.BodyAsync().This method discards all its resources, calling any method on disposed APIRequestContext will throw an exception.

用法

¥Usage

await ApiRequestContext.DisposeAsync(options);

参数

¥Arguments

  • options ApiRequestContextDisposeOptions?(可选)

    ¥options ApiRequestContextDisposeOptions? (optional)

    • Reason string? (optional) Added in: v1.45#

报告上下文处置中断操作的原因。

¥The reason to be reported to the operations interrupted by the context disposal.

返回

¥Returns


FetchAsync

Added in: v1.16 apiRequestContext.FetchAsync

发送 HTTP(S) 请求并返回其响应。该方法将从上下文填充请求 cookie,并从响应更新上下文 cookie。该方法将自动遵循重定向。

¥Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.

用法

¥Usage

JSON 对象可以直接传递给请求:

¥JSON objects can be passed directly to the request:

var data = new Dictionary<string, object>() {
{ "title", "Book Title" },
{ "body", "John Doe" }
};
await Request.FetchAsync("https://example.com/api/createBook", new() { Method = "post", DataObject = data });

在请求正文中发送文件的常用方法是通过指定 multipart 参数将它们作为具有 multipart/form-data 编码的表单字段上传:

¥The common way to send file(s) in the body of a request is to upload them as form fields with multipart/form-data encoding, by specifiying the multipart parameter:

var file = new FilePayload()
{
Name = "f.js",
MimeType = "text/javascript",
Buffer = System.Text.Encoding.UTF8.GetBytes("console.log(2022);")
};
var multipart = Context.APIRequest.CreateFormData();
multipart.Set("fileField", file);
await Request.FetchAsync("https://example.com/api/uploadScript", new() { Method = "post", Multipart = multipart });

参数

¥Arguments

从中获取所有参数的目标 URL 或请求。

¥Target URL or Request to get all parameters from.

  • options ApiRequestContextFetchOptions?(可选)

    ¥options ApiRequestContextFetchOptions? (optional)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (optional)#

允许设置请求的发布数据。如果 data 参数是一个对象,它将被序列化为 json 字符串,如果没有显式设置,content-type header 将被设置为 application/json。否则,如果未显式设置,content-type 标头将设置为 application/octet-stream

¥Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

  • FailOnStatusCode bool? (optional)#

是否抛出除 2xx 和 3xx 之外的响应代码。默认情况下,为所有状态代码返回响应对象。

¥Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

提供一个对象,该对象将使用 application/x-www-form-urlencoded 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 application/x-www-form-urlencoded

¥Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

允许设置 HTTP 标头。这些标头将应用于获取的请求以及由其发起的任何重定向。

¥Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

  • IgnoreHTTPSErrors bool? (optional)#

发送网络请求时是否忽略 HTTPS 错误。默认为 false

¥Whether to ignore HTTPS errors when sending network requests. Defaults to false.

  • MaxRedirects int? (optional) Added in: v1.26#

自动遵循的请求重定向的最大数量。如果超过数量将会抛出错误。默认为 20。通过 0 不遵循重定向。

¥Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

  • MaxRetries int? (optional) Added in: v1.46#

应重试网络错误的最大次数。当前仅重试 ECONNRESET 错误。不根据 HTTP 响应代码重试。如果超出限制,将引发错误。默认为 0 - 不重试。

¥Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.

如果设置更改了获取方法(例如 PUTPOST)。如果未指定,则使用 GET 方法。

¥If set changes the fetch method (e.g. PUT or POST). If not specified, GET method is used.

提供一个对象,该对象将使用 multipart/form-data 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。

¥Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • ParamsString string? (optional) Added in: v1.47#

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • Timeout [float]? (optional)#

请求超时(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

返回

¥Returns


GetAsync

Added in: v1.16 apiRequestContext.GetAsync

发送 HTTP(S) GET 请求并返回其响应。该方法将从上下文填充请求 cookie,并从响应更新上下文 cookie。该方法将自动遵循重定向。

¥Sends HTTP(S) GET request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.

用法

¥Usage

请求参数可以使用 params 选项进行配置,它们将被序列化为 URL 搜索参数:

¥Request parameters can be configured with params option, they will be serialized into the URL search parameters:

var queryParams = new Dictionary<string, object>()
{
{ "isbn", "1234" },
{ "page", 23 },
};
await request.GetAsync("https://example.com/api/getText", new() { Params = queryParams });

参数

¥Arguments

目标网址。

¥Target URL.

  • options ApiRequestContextGetOptions?(可选)

    ¥options ApiRequestContextGetOptions? (optional)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (optional) Added in: v1.26#

允许设置请求的发布数据。如果 data 参数是一个对象,它将被序列化为 json 字符串,如果没有显式设置,content-type header 将被设置为 application/json。否则,如果未显式设置,content-type 标头将设置为 application/octet-stream

¥Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

  • FailOnStatusCode bool? (optional)#

是否抛出除 2xx 和 3xx 之外的响应代码。默认情况下,为所有状态代码返回响应对象。

¥Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

提供一个对象,该对象将使用 application/x-www-form-urlencoded 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 application/x-www-form-urlencoded

¥Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

允许设置 HTTP 标头。这些标头将应用于获取的请求以及由其发起的任何重定向。

¥Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

  • IgnoreHTTPSErrors bool? (optional)#

发送网络请求时是否忽略 HTTPS 错误。默认为 false

¥Whether to ignore HTTPS errors when sending network requests. Defaults to false.

  • MaxRedirects int? (optional) Added in: v1.26#

自动遵循的请求重定向的最大数量。如果超过数量将会抛出错误。默认为 20。通过 0 不遵循重定向。

¥Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

  • MaxRetries int? (optional) Added in: v1.46#

应重试网络错误的最大次数。当前仅重试 ECONNRESET 错误。不根据 HTTP 响应代码重试。如果超出限制,将引发错误。默认为 0 - 不重试。

¥Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.

  • Multipart FormData? (optional) Added in: v1.26#

提供一个对象,该对象将使用 multipart/form-data 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。

¥Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • ParamsString string? (optional) Added in: v1.47#

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • Timeout [float]? (optional)#

请求超时(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

返回

¥Returns


HeadAsync

Added in: v1.16 apiRequestContext.HeadAsync

发送 HTTP(S) HEAD 请求并返回其响应。该方法将从上下文填充请求 cookie,并从响应更新上下文 cookie。该方法将自动遵循重定向。

¥Sends HTTP(S) HEAD request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.

用法

¥Usage

await ApiRequestContext.HeadAsync(url, options);

参数

¥Arguments

目标网址。

¥Target URL.

  • options ApiRequestContextHeadOptions?(可选)

    ¥options ApiRequestContextHeadOptions? (optional)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (optional) Added in: v1.26#

允许设置请求的发布数据。如果 data 参数是一个对象,它将被序列化为 json 字符串,如果没有显式设置,content-type header 将被设置为 application/json。否则,如果未显式设置,content-type 标头将设置为 application/octet-stream

¥Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

  • FailOnStatusCode bool? (optional)#

是否抛出除 2xx 和 3xx 之外的响应代码。默认情况下,为所有状态代码返回响应对象。

¥Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

提供一个对象,该对象将使用 application/x-www-form-urlencoded 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 application/x-www-form-urlencoded

¥Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

允许设置 HTTP 标头。这些标头将应用于获取的请求以及由其发起的任何重定向。

¥Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

  • IgnoreHTTPSErrors bool? (optional)#

发送网络请求时是否忽略 HTTPS 错误。默认为 false

¥Whether to ignore HTTPS errors when sending network requests. Defaults to false.

  • MaxRedirects int? (optional) Added in: v1.26#

自动遵循的请求重定向的最大数量。如果超过数量将会抛出错误。默认为 20。通过 0 不遵循重定向。

¥Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

  • MaxRetries int? (optional) Added in: v1.46#

应重试网络错误的最大次数。当前仅重试 ECONNRESET 错误。不根据 HTTP 响应代码重试。如果超出限制,将引发错误。默认为 0 - 不重试。

¥Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.

  • Multipart FormData? (optional) Added in: v1.26#

提供一个对象,该对象将使用 multipart/form-data 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。

¥Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • ParamsString string? (optional) Added in: v1.47#

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • Timeout [float]? (optional)#

请求超时(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

返回

¥Returns


PatchAsync

Added in: v1.16 apiRequestContext.PatchAsync

发送 HTTP(S) PATCH 请求并返回其响应。该方法将从上下文填充请求 cookie,并从响应更新上下文 cookie。该方法将自动遵循重定向。

¥Sends HTTP(S) PATCH request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.

用法

¥Usage

await ApiRequestContext.PatchAsync(url, options);

参数

¥Arguments

目标网址。

¥Target URL.

  • options ApiRequestContextPatchOptions?(可选)

    ¥options ApiRequestContextPatchOptions? (optional)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (optional)#

允许设置请求的发布数据。如果 data 参数是一个对象,它将被序列化为 json 字符串,如果没有显式设置,content-type header 将被设置为 application/json。否则,如果未显式设置,content-type 标头将设置为 application/octet-stream

¥Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

  • FailOnStatusCode bool? (optional)#

是否抛出除 2xx 和 3xx 之外的响应代码。默认情况下,为所有状态代码返回响应对象。

¥Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

提供一个对象,该对象将使用 application/x-www-form-urlencoded 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 application/x-www-form-urlencoded

¥Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

允许设置 HTTP 标头。这些标头将应用于获取的请求以及由其发起的任何重定向。

¥Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

  • IgnoreHTTPSErrors bool? (optional)#

发送网络请求时是否忽略 HTTPS 错误。默认为 false

¥Whether to ignore HTTPS errors when sending network requests. Defaults to false.

  • MaxRedirects int? (optional) Added in: v1.26#

自动遵循的请求重定向的最大数量。如果超过数量将会抛出错误。默认为 20。通过 0 不遵循重定向。

¥Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

  • MaxRetries int? (optional) Added in: v1.46#

应重试网络错误的最大次数。当前仅重试 ECONNRESET 错误。不根据 HTTP 响应代码重试。如果超出限制,将引发错误。默认为 0 - 不重试。

¥Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.

提供一个对象,该对象将使用 multipart/form-data 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。

¥Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • ParamsString string? (optional) Added in: v1.47#

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • Timeout [float]? (optional)#

请求超时(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

返回

¥Returns


PostAsync

Added in: v1.16 apiRequestContext.PostAsync

发送 HTTP(S) POST 请求并返回其响应。该方法将从上下文填充请求 cookie,并从响应更新上下文 cookie。该方法将自动遵循重定向。

¥Sends HTTP(S) POST request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.

用法

¥Usage

JSON 对象可以直接传递给请求:

¥JSON objects can be passed directly to the request:

var data = new Dictionary<string, object>() {
{ "firstName", "John" },
{ "lastName", "Doe" }
};
await request.PostAsync("https://example.com/api/createBook", new() { DataObject = data });

要将表单数据发送到服务器,请使用 form 选项。它的值将以 application/x-www-form-urlencoded 编码编码到请求体中(参见下面如何使用 multipart/form-data 形式编码发送文件):

¥To send form data to the server use form option. Its value will be encoded into the request body with application/x-www-form-urlencoded encoding (see below how to use multipart/form-data form encoding to send files):

var formData = Context.APIRequest.CreateFormData();
formData.Set("title", "Book Title");
formData.Set("body", "John Doe");
await request.PostAsync("https://example.com/api/findBook", new() { Form = formData });

在请求正文中发送文件的常见方法是将它们作为具有 multipart/form-data 编码的表单字段上传。使用 FormData 构造请求主体并将其作为 multipart 参数传递给请求:

¥The common way to send file(s) in the body of a request is to upload them as form fields with multipart/form-data encoding. Use FormData to construct request body and pass it to the request as multipart parameter:

var file = new FilePayload()
{
Name = "f.js",
MimeType = "text/javascript",
Buffer = System.Text.Encoding.UTF8.GetBytes("console.log(2022);")
};
var multipart = Context.APIRequest.CreateFormData();
multipart.Set("fileField", file);
await request.PostAsync("https://example.com/api/uploadScript", new() { Multipart = multipart });

参数

¥Arguments

目标网址。

¥Target URL.

  • options ApiRequestContextPostOptions?(可选)

    ¥options ApiRequestContextPostOptions? (optional)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (optional)#

允许设置请求的发布数据。如果 data 参数是一个对象,它将被序列化为 json 字符串,如果没有显式设置,content-type header 将被设置为 application/json。否则,如果未显式设置,content-type 标头将设置为 application/octet-stream

¥Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

  • FailOnStatusCode bool? (optional)#

是否抛出除 2xx 和 3xx 之外的响应代码。默认情况下,为所有状态代码返回响应对象。

¥Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

提供一个对象,该对象将使用 application/x-www-form-urlencoded 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 application/x-www-form-urlencoded

¥Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

允许设置 HTTP 标头。这些标头将应用于获取的请求以及由其发起的任何重定向。

¥Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

  • IgnoreHTTPSErrors bool? (optional)#

发送网络请求时是否忽略 HTTPS 错误。默认为 false

¥Whether to ignore HTTPS errors when sending network requests. Defaults to false.

  • MaxRedirects int? (optional) Added in: v1.26#

自动遵循的请求重定向的最大数量。如果超过数量将会抛出错误。默认为 20。通过 0 不遵循重定向。

¥Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

  • MaxRetries int? (optional) Added in: v1.46#

应重试网络错误的最大次数。当前仅重试 ECONNRESET 错误。不根据 HTTP 响应代码重试。如果超出限制,将引发错误。默认为 0 - 不重试。

¥Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.

提供一个对象,该对象将使用 multipart/form-data 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。

¥Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • ParamsString string? (optional) Added in: v1.47#

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • Timeout [float]? (optional)#

请求超时(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

返回

¥Returns


PutAsync

Added in: v1.16 apiRequestContext.PutAsync

发送 HTTP(S) PUT 请求并返回其响应。该方法将从上下文填充请求 cookie,并从响应更新上下文 cookie。该方法将自动遵循重定向。

¥Sends HTTP(S) PUT request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.

用法

¥Usage

await ApiRequestContext.PutAsync(url, options);

参数

¥Arguments

目标网址。

¥Target URL.

  • options ApiRequestContextPutOptions?(可选)

    ¥options ApiRequestContextPutOptions? (optional)

    • Data|DataByte|DataObject string? | byte[]? | [object]? (optional)#

允许设置请求的发布数据。如果 data 参数是一个对象,它将被序列化为 json 字符串,如果没有显式设置,content-type header 将被设置为 application/json。否则,如果未显式设置,content-type 标头将设置为 application/octet-stream

¥Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string and content-type header will be set to application/json if not explicitly set. Otherwise the content-type header will be set to application/octet-stream if not explicitly set.

  • FailOnStatusCode bool? (optional)#

是否抛出除 2xx 和 3xx 之外的响应代码。默认情况下,为所有状态代码返回响应对象。

¥Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.

提供一个对象,该对象将使用 application/x-www-form-urlencoded 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 application/x-www-form-urlencoded

¥Provides an object that will be serialized as html form using application/x-www-form-urlencoded encoding and sent as this request body. If this parameter is specified content-type header will be set to application/x-www-form-urlencoded unless explicitly provided.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

允许设置 HTTP 标头。这些标头将应用于获取的请求以及由其发起的任何重定向。

¥Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by it.

  • IgnoreHTTPSErrors bool? (optional)#

发送网络请求时是否忽略 HTTPS 错误。默认为 false

¥Whether to ignore HTTPS errors when sending network requests. Defaults to false.

  • MaxRedirects int? (optional) Added in: v1.26#

自动遵循的请求重定向的最大数量。如果超过数量将会抛出错误。默认为 20。通过 0 不遵循重定向。

¥Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is exceeded. Defaults to 20. Pass 0 to not follow redirects.

  • MaxRetries int? (optional) Added in: v1.46#

应重试网络错误的最大次数。当前仅重试 ECONNRESET 错误。不根据 HTTP 响应代码重试。如果超出限制,将引发错误。默认为 0 - 不重试。

¥Maximum number of times network errors should be retried. Currently only ECONNRESET error is retried. Does not retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to 0 - no retries.

提供一个对象,该对象将使用 multipart/form-data 编码序列化为 html 表单,并作为此请求正文发送。如果指定此参数,除非明确提供,否则 content-type 标头将设置为 multipart/form-data。文件值可以作为包含文件名、MIME 类型及其内容的类文件对象传递。

¥Provides an object that will be serialized as html form using multipart/form-data encoding and sent as this request body. If this parameter is specified content-type header will be set to multipart/form-data unless explicitly provided. File values can be passed as file-like object containing file name, mime-type and its content.

可以通过 ApiRequestContext.CreateFormData 创建 FormData 的实例。

¥An instance of FormData can be created via ApiRequestContext.CreateFormData.

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • ParamsString string? (optional) Added in: v1.47#

与 URL 一起发送的查询参数。

¥Query parameters to be sent with the URL.

  • Timeout [float]? (optional)#

请求超时(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

¥Request timeout in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

返回

¥Returns


StorageStateAsync

Added in: v1.16 apiRequestContext.StorageStateAsync

返回此请求上下文的存储状态,包含当前 cookie 和本地存储快照(如果已传递给构造函数)。

¥Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor.

用法

¥Usage

await ApiRequestContext.StorageStateAsync(options);

参数

¥Arguments

  • options ApiRequestContextStorageStateOptions?(可选)

    ¥options ApiRequestContextStorageStateOptions? (optional)

    • IndexedDB bool? (optional) Added in: v1.51#

设置为 true 以将 IndexedDB 包含在存储状态快照中。

¥Set to true to include IndexedDB in the storage state snapshot.

保存存储状态的文件路径。如果 路径 是相对路径,则相对于当前工作目录进行解析。如果未提供路径,仍会返回存储状态,但不会保存到磁盘。

¥The file path to save the storage state to. If Path is a relative path, then it is resolved relative to current working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.

返回

¥Returns