-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
.pr_agent_accepted_suggestions
| PR 2368 (2026-03-05) |
[correctness] Broken BaseUrl example
Broken BaseUrl example
The v114 configuration page shows setting `BaseUrl` using a non-existent `Url` type and uses a comma instead of a statement terminator, so the sample won’t compile and misrepresents the API (`BaseUrl` is a `Uri?`).The v114 docs show an invalid C# snippet for configuring RestClientOptions (Url type doesn’t exist; comma used instead of statement terminator).
RestClientOptions.BaseUrl is Uri? and RestSharp constructors accept Uri/string.
- docs/versioned_docs/version-v114/advanced/configuration.md[63-67]
Replace with something like:
[correctness] Invalid serializer lambda
Invalid serializer lambda
The v114 serialization page contains a `configureSerialization:` argument with a stray semicolon inside the argument expression, making the snippet invalid C# as written.A code sample uses an expression lambda with a trailing ; inside the argument list, which makes the snippet not compile.
configureSerialization takes a ConfigureSerialization delegate. The argument must be a valid lambda expression.
- docs/versioned_docs/version-v114/advanced/serialization.md[16-21]
Either:
[correctness] HttpClient reuse section wrong
HttpClient reuse section wrong
The v114 docs claim `BaseAddress` and `MaxTimeout` are the options that apply when reusing an `HttpClient`, but RestSharp uses `RestClientOptions.BaseUrl` (populated from `httpClient.BaseAddress`) and `MaxTimeout` doesn’t exist.The guidance for reusing HttpClient references properties that don’t match the current API (BaseAddress/MaxTimeout).
When an HttpClient is provided, RestSharp maps httpClient.BaseAddress to RestClientOptions.BaseUrl if BaseUrl is unset.
- docs/versioned_docs/version-v114/usage/client.md[67-72]
Adjust bullets to something like:
-
BaseUrl(if not set, it will be taken fromhttpClient.BaseAddress) -
Timeout(request/client timeout behavior) UserAgent-
Expect100Continue(and removeMaxTimeoutmentions)
[correctness] Example uses wrong ctor
Example uses wrong ctor
The v114 usage example shows creating `RestClient` with an `IOptions` value and defines `TwitterClientOptions` with invalid class/record syntax; the snippet won’t compile and doesn’t match available `RestClient` constructors.The example constructs RestClient with the wrong argument type (IOptions<TwitterClientOptions>), and the options type declaration is syntactically incorrect for many C# versions.
RestClient expects RestClientOptions (or other supported overloads like Uri, string, HttpClient).
- docs/versioned_docs/version-v114/usage/example.md[78-85]
Example:
| PR 2363 (2026-03-01) |
[correctness] ExpectContinue missing on redirects
ExpectContinue missing on redirects
RestClientOptions.Expect100Continue is applied to the initial HttpRequestMessage but not to redirect follow-up HttpRequestMessages created during manual redirect handling. As a result, redirected requests may ignore the Expect100Continue option (behavior regression vs when it was applied via HttpClient default headers).RestClientOptions.Expect100Continue is only applied to the initial HttpRequestMessage in ExecuteRequestAsync. When redirects are followed, RestSharp creates a new HttpRequestMessage in CreateRedirectMessage, but it does not set Headers.ExpectContinue, so redirected requests can ignore the option.
RestSharp performs redirects manually (AllowAutoRedirect = false) and uses CreateRedirectMessage for each hop.
- src/RestSharp/RestClient.Async.cs[265-290]
- src/RestSharp/RestClient.Async.cs[137-143]
- test/RestSharp.Tests.Integrated/CookieRedirectTests.cs[194-220] (or add a new integrated redirect test using
/echo-requestto assert theExpectheader on the final hop)
| PR 2362 (2026-03-01) |
[reliability] AuthenticatorBase can't cancel work
AuthenticatorBase can't cancel work
AuthenticatorBase accepts a CancellationToken but does not forward it to an overridable method, so derived authenticators cannot implement cancellable auth work via the base class’ template method.AuthenticatorBase cannot propagate cancellation because GetAuthenticationParameter doesn’t accept a CancellationToken.
While built-in stampers are synchronous, consumers may derive from AuthenticatorBase for authenticators that do async work.
- src/RestSharp/Authenticators/AuthenticatorBase.cs[17-23]
- Add a new virtual method:
protected virtual ValueTask<Parameter> GetAuthenticationParameter(string accessToken, CancellationToken cancellationToken)- default implementation calls the existing abstract method.
- Update
Authenticateto call the new overload, passingcancellationToken. This is additive for derived classes (no breaking override required) while enabling cancellation-aware implementations.
[reliability] `_getToken` ignores cancellation
`_getToken` ignores cancellation
`OAuth2TokenAuthenticator` invokes the token provider with `CancellationToken.None`, so token acquisition cannot be cancelled. This violates the requirement that the delegate-based lifecycle authenticator supports cancellation via `CancellationToken`.OAuth2TokenAuthenticator calls the user-supplied Func&amp;lt;CancellationToken, Task&amp;lt;OAuth2Token&amp;gt;&amp;gt; with CancellationToken.None, so token acquisition cannot be cancelled.
Compliance requires that the delegate-based lifecycle authenticator be cancellable via CancellationToken. RestSharp&#x27;s IAuthenticator.Authenticate(IRestClient, RestRequest) does not currently accept a cancellation token, so you will need to route the execution cancellation token to the authenticator via an alternative mechanism (e.g., store it on the RestRequest before calling Authenticate, or introduce a compatible authenticator hook that includes a token).
- src/RestSharp/Authenticators/OAuth2/OAuth2TokenAuthenticator.cs[39-56]
[reliability] `_getToken` ignores cancellation
`_getToken` ignores cancellation
`OAuth2TokenAuthenticator` invokes the token provider with `CancellationToken.None`, so token acquisition cannot be cancelled. This violates the requirement that the delegate-based lifecycle authenticator supports cancellation via `CancellationToken`.OAuth2TokenAuthenticator calls the user-supplied Func&amp;amp;lt;CancellationToken, Task&amp;amp;lt;OAuth2Token&amp;amp;gt;&amp;amp;gt; with CancellationToken.None, so token acquisition cannot be cancelled.
Compliance requires that the delegate-based lifecycle authenticator be cancellable via CancellationToken. RestSharp&amp;#x27;s IAuthenticator.Authenticate(IRestClient, RestRequest) does not currently accept a cancellation token, so you will need to route the execution cancellation token to the authenticator via an alternative mechanism (e.g., store it on the RestRequest before calling Authenticate, or introduce a compatible authenticator hook that includes a token).
- src/RestSharp/Authenticators/OAuth2/OAuth2TokenAuthenticator.cs[39-56]
[reliability] Callback deadlock under lock
Callback deadlock under lock
OnTokenRefreshed is invoked while holding the SemaphoreSlim refresh lock. If the callback triggers another request using the same authenticator (directly or indirectly), it can deadlock; even without deadlock it blocks all concurrent requests waiting for the lock.OnTokenRefreshed is executed while holding the internal refresh SemaphoreSlim. User code in that callback can block, perform I/O, or re-enter RestSharp and cause deadlocks. It also unnecessarily blocks all other waiting requests.
Both OAuth2ClientCredentialsAuthenticator and OAuth2RefreshTokenAuthenticator call _request.OnTokenRefreshed?.Invoke(tokenResponse) before releasing _lock.
- src/RestSharp/Authenticators/OAuth2/OAuth2ClientCredentialsAuthenticator.cs[57-100]
- src/RestSharp/Authenticators/OAuth2/OAuth2RefreshTokenAuthenticator.cs[70-114]
[reliability] Callback deadlock under lock
Callback deadlock under lock
OnTokenRefreshed is invoked while holding the SemaphoreSlim refresh lock. If the callback triggers another request using the same authenticator (directly or indirectly), it can deadlock; even without deadlock it blocks all concurrent requests waiting for the lock.OnTokenRefreshed is executed while holding the internal refresh SemaphoreSlim. User code in that callback can block, perform I/O, or re-enter RestSharp and cause deadlocks. It also unnecessarily blocks all other waiting requests.
Both OAuth2ClientCredentialsAuthenticator and OAuth2RefreshTokenAuthenticator call _request.OnTokenRefreshed?.Invoke(tokenResponse) before releasing _lock.
- src/RestSharp/Authenticators/OAuth2/OAuth2ClientCredentialsAuthenticator.cs[57-100]
- src/RestSharp/Authenticators/OAuth2/OAuth2RefreshTokenAuthenticator.cs[70-114]
[reliability] Missing expires_in causes refresh storm
Missing expires_in causes refresh storm
OAuth2TokenResponse.ExpiresIn is a non-nullable int; when expires_in is omitted (allowed by RFC 6749), it deserializes to 0 and the code treats the token as immediately expired, causing a token endpoint call on every request.When the token endpoint omits expires_in, deserialization yields 0 and the authenticators treat the token as expired immediately. This can cause a refresh/token acquisition call for every request.
OAuth2TokenResponse.ExpiresIn is a non-nullable int and expiry computation in authenticators uses it unconditionally.
- src/RestSharp/Authenticators/OAuth2/OAuth2TokenResponse.cs[23-32]
- src/RestSharp/Authenticators/OAuth2/OAuth2ClientCredentialsAuthenticator.cs[86-96]
- src/RestSharp/Authenticators/OAuth2/OAuth2RefreshTokenAuthenticator.cs[96-103]
[reliability] Missing expires_in causes refresh storm
Missing expires_in causes refresh storm
OAuth2TokenResponse.ExpiresIn is a non-nullable int; when expires_in is omitted (allowed by RFC 6749), it deserializes to 0 and the code treats the token as immediately expired, causing a token endpoint call on every request.When the token endpoint omits expires_in, deserialization yields 0 and the authenticators treat the token as expired immediately. This can cause a refresh/token acquisition call for every request.
OAuth2TokenResponse.ExpiresIn is a non-nullable int and expiry computation in authenticators uses it unconditionally.
- src/RestSharp/Authenticators/OAuth2/OAuth2TokenResponse.cs[23-32]
- src/RestSharp/Authenticators/OAuth2/OAuth2ClientCredentialsAuthenticator.cs[86-96]
- src/RestSharp/Authenticators/OAuth2/OAuth2RefreshTokenAuthenticator.cs[96-103]
[correctness] Refresh flow ignores Scope
Refresh flow ignores Scope
OAuth2RefreshTokenAuthenticator never sends OAuth2TokenRequest.Scope, unlike the client-credentials authenticator. Some servers require/validate scope on refresh, so refresh may fail or return unexpected scope.OAuth2RefreshTokenAuthenticator does not include scope in the refresh request even when configured.
OAuth2TokenRequest exposes Scope, and client-credentials flow includes it; refresh-token flow does not.
- src/RestSharp/Authenticators/OAuth2/OAuth2RefreshTokenAuthenticator.cs[76-86]
- src/RestSharp/Authenticators/OAuth2/OAuth2TokenRequest.cs[50-54]
[correctness] Token type hardcoded Bearer
Token type hardcoded Bearer
Client-credentials and refresh-token authenticators always emit an Authorization header with "Bearer" and ignore token_type from the token endpoint response; this reduces compatibility with non-Bearer token types.Lifecycle authenticators hardcode Bearer and ignore the token_type returned by the token endpoint.
OAuth2TokenResponse includes TokenType, and existing OAuth2 header authenticator supports a configurable token type.
- src/RestSharp/Authenticators/OAuth2/OAuth2ClientCredentialsAuthenticator.cs[48-51]
- src/RestSharp/Authenticators/OAuth2/OAuth2RefreshTokenAuthenticator.cs[61-64]
- src/RestSharp/Authenticators/OAuth2/OAuth2TokenResponse.cs[24-32]
[correctness] Refresh flow ignores Scope
Refresh flow ignores Scope
OAuth2RefreshTokenAuthenticator never sends OAuth2TokenRequest.Scope, unlike the client-credentials authenticator. Some servers require/validate scope on refresh, so refresh may fail or return unexpected scope.OAuth2RefreshTokenAuthenticator does not include scope in the refresh request even when configured.
OAuth2TokenRequest exposes Scope, and client-credentials flow includes it; refresh-token flow does not.
- src/RestSharp/Authenticators/OAuth2/OAuth2RefreshTokenAuthenticator.cs[76-86]
- src/RestSharp/Authenticators/OAuth2/OAuth2TokenRequest.cs[50-54]
[correctness] Token type hardcoded Bearer
Token type hardcoded Bearer
Client-credentials and refresh-token authenticators always emit an Authorization header with "Bearer" and ignore token_type from the token endpoint response; this reduces compatibility with non-Bearer token types.Lifecycle authenticators hardcode Bearer and ignore the token_type returned by the token endpoint.
OAuth2TokenResponse includes TokenType, and existing OAuth2 header authenticator supports a configurable token type.
- src/RestSharp/Authenticators/OAuth2/OAuth2ClientCredentialsAuthenticator.cs[48-51]
- src/RestSharp/Authenticators/OAuth2/OAuth2RefreshTokenAuthenticator.cs[61-64]
- src/RestSharp/Authenticators/OAuth2/OAuth2TokenResponse.cs[24-32]
| PR 2360 (2026-02-27) |
[reliability] Redirect sends duplicate `Cookie` headers
Redirect sends duplicate `Cookie` headers
Redirect requests add cookies from both `request.CookieContainer` and `Options.CookieContainer`, but `AddCookieHeaders` appends a new `Cookie` header parameter each call, leading to multiple `Cookie` header values and potential duplicated cookies. This can cause invalid Cookie headers and redirect loops when both containers contain overlapping cookies.Redirect requests can emit multiple Cookie header values (and duplicate cookie entries) when both request.CookieContainer and Options.CookieContainer are used, because RequestHeaders.AddCookieHeaders appends a new Cookie header parameter each time.
This violates the requirement to avoid duplicated cookies when multiple cookie containers are configured, and can lead to invalid Cookie headers and redirect loops.
- src/RestSharp/RestClient.Async.cs[265-272]
- src/RestSharp/Request/RequestHeaders.cs[43-60]
- src/RestSharp/Request/HttpRequestMessageExtensions.cs[22-33]
[correctness] Redirect misses Host/CacheControl
Redirect misses Host/CacheControl
Redirect follow-up requests are created without reapplying Options.BaseHost and request/Options CachePolicy, so redirected hops may be sent with a different Host header and without intended cache directives.Redirect-followup requests do not reapply Options.BaseHost and request.CachePolicy ?? Options.CachePolicy, even though those settings are applied to the initial request message.
ExecuteRequestAsync applies Host and CacheControl only on the initial HttpRequestMessage. When following redirects, a new HttpRequestMessage is created but those fields are not restored.
- src/RestSharp/RestClient.Async.cs[216-229]
- src/RestSharp/RestClient.Async.cs[147-152]
After creating the redirect HttpRequestMessage, set:
message.Headers.Host = Options.BaseHost;-
message.Headers.CacheControl = request.CachePolicy ?? Options.CachePolicy;(and any other per-message settings that should remain consistent across hops).
| PR 2358 (2026-02-26) |
[correctness] RestResponse not immutable
RestResponse not immutable
CLAUDE.md claims RestResponse/RestResponse are “immutable”, but the actual types expose public setters (including `Data`). This is misleading guidance and can lead to incorrect assumptions in new code/tests (e.g., treating responses as safe to share or as value objects).CLAUDE.md states that RestResponse/RestResponse&lt;T&gt; are immutable, but the implementation has public setters (including Data). This is incorrect guidance and can mislead contributors/agents.
[GenerateClone] generates clone/factory helpers; it does not enforce immutability.
- CLAUDE.md[46-49]
| PR 2357 (2026-02-26) |
[correctness] Quoting not applied to body parts
Quoting not applied to body parts
MultipartFormQuoteParameters now defaults to true, but it is only used when adding GetOrPostParameter parts; BodyParameter parts are still added without applying the quote behavior, producing inconsistent Content-Disposition formatting within the same multipart request.MultipartFormQuoteParameters now defaults to true, but it is only used when adding GetOrPostParameter parts. Multipart body parts added via BodyParameter still call mpContent.Add(bodyContent, name) without applying the quote behavior, resulting in mixed quoted/unquoted Content-Disposition name parameters.
The PR intends to quote multipart form parameter names by default, but current implementation only affects one code path.
- src/RestSharp/Request/RequestContent.cs[133-147]
- src/RestSharp/Request/RequestContent.cs[159-171]
- test/RestSharp.Tests.Integrated/MultipartFormDataTests.cs[38-46]
- src/RestSharp/Request/RestRequest.cs[88-92]
| PR 2351 (2026-02-26) |
[reliability] Pending cookies lack error handling
Pending cookies lack error handling
`cookieContainer.Add(url, cookie)` can throw (for example `CookieException`) and currently happens outside the existing request `try/catch`, so a bad cookie can crash request execution. This violates the requirement to handle failure points and edge cases gracefully.ExecuteRequestAsync applies request.PendingCookies via cookieContainer.Add(url, cookie) without any exception handling, and this code runs outside the existing try/catch that wraps HttpClient.SendAsync. Invalid cookies (or unexpected nulls) can throw (e.g., CookieException) and crash the request.
There is already precedent in the codebase for not failing the request when cookie parsing fails (see CookieContainerExtensions.AddCookies which catches CookieException). Pending cookies should be handled with similar robustness.
- src/RestSharp/RestClient.Async.cs[130-136]
- src/RestSharp/Extensions/CookieContainerExtensions.cs[19-27]
[correctness] Cookies hidden from hooks
Cookies hidden from hooks
AddCookie(name,value) stores cookies in an internal pending list and only resolves them into CookieContainer after request interceptors and authenticators run. Custom interceptors/authenticators that read request.CookieContainer (or otherwise expect request cookies to be part of request state) will not see these cookies and may misbehave (eg signing/auth decisions made without cookies).AddCookie(name, value) stores cookies in an internal pending list and only moves them into request.CookieContainer late in ExecuteRequestAsync, after request interceptors (BeforeRequest) and IAuthenticator.Authenticate have already run. This makes those cookies invisible to hook code that needs to read request cookies.
- The 4-parameter overload populates
request.CookieContainerimmediately; the new 2-parameter overload does not. - Interceptors/authenticators operate on
RestRequestand can reasonably expect request cookies to be part of observable request state.
- src/RestSharp/Request/RestRequestExtensions.cs[127-148]
- src/RestSharp/Request/RestRequest.cs[75-76]
- src/RestSharp/Request/RestRequest.cs[266-270]
- src/RestSharp/RestClient.Async.cs[130-135]
[reliability] Pending cookies never cleared
Pending cookies never cleared
PendingCookies are transferred into the request CookieContainer on every execution, but the pending list is never cleared or marked as resolved. If a RestRequest is re-executed (or retried), the same Cookie objects will be re-added repeatedly, causing avoidable overhead and potential re-add edge cases.PendingCookies are added to request.CookieContainer during execution but the pending list is never cleared. Re-executing the same RestRequest (or retry flows) will repeat the add loop unnecessarily.
Once cookies are added to request.CookieContainer, they will already be available for AddCookieHeaders(...) in future executions, so the pending list is redundant.
- src/RestSharp/RestClient.Async.cs[130-135]
- src/RestSharp/Request/RestRequest.cs[75-76]
- src/RestSharp/Request/RestRequest.cs[266-270]
[correctness] CookieContainer docs inaccurate
CookieContainer docs inaccurate
The usage docs imply that calling AddCookie creates the request CookieContainer, but the new 2-parameter overload does not set CookieContainer until execution time. This can mislead users who check request.CookieContainer immediately after calling AddCookie(name,value).Docs currently suggest the request CookieContainer is created when calling AddCookie, but the new 2-parameter overload does not assign CookieContainer until request execution.
This is primarily a documentation clarity issue to prevent confusion when users inspect request.CookieContainer right after calling AddCookie(name, value).
- docs/docs/usage/request.md[230-240]
- docs/versioned_docs/version-v110/usage/usage.md[233-243]
- docs/versioned_docs/version-v111/usage/request.md[211-221]
- docs/versioned_docs/version-v112/usage/request.md[230-240]
- docs/versioned_docs/version-v113/usage/request.md[230-240]
| PR 2349 (2026-02-25) |
[correctness] Multi-value default headers lost
Multi-value default headers lost
The new default-parameter merge deduplicates by `Name`+`Type`, which drops additional default headers/parameters that intentionally share the same name (e.g., multiple header values). This can cause missing default headers in `RestResponse.Request.Parameters` and potentially alters the headers actually sent.The merge of DefaultParameters into request.Parameters currently deduplicates purely by Name + Type, which drops additional default headers/parameters that intentionally share a name (e.g., multiple HttpHeader values). This can prevent all configured default headers from appearing in response.Request.Parameters and can change what is actually sent.
RestClientOptions.AllowMultipleDefaultParametersWithSameName explicitly does not apply to headers (multiple values are allowed), and DefaultParameters.AddParameter also allows duplicates for HttpHeader and certain multi-parameter types. The merge should respect those semantics.
- src/RestSharp/RestClient.Async.cs[104-109]
[correctness] BuildUri skips defaults
BuildUri skips defaults
`BuildUriWithoutQueryParameters` and `GetRequestQuery` no longer include `client.DefaultParameters`, so `client.BuildUri*` omits default URL segments and query parameters unless the request was previously executed/mutated. This is a behavioral regression for a public API that’s expected to reflect defaults used “on every request.”BuildUri* no longer considers client.DefaultParameters, so URLs built via client.BuildUri() / BuildUriString() can omit default query params and URL segments.
These methods are public API and are commonly used to inspect/preview the final request URI.
- src/RestSharp/BuildUriExtensions.cs[50-58]
- src/RestSharp/BuildUriExtensions.cs[66-70]
- src/RestSharp/Request/UriExtensions.cs[50-66]
- src/RestSharp/IRestClient.cs[31-35]
[correctness] OAuth1 skips defaults
OAuth1 skips defaults
OAuth1 signing no longer includes `client.DefaultParameters` when `OAuth1Authenticator.Authenticate` (or `AddOAuthData`) is called directly, producing incorrect signatures when defaults contain query/post params. This is a realistic scenario since tests call `Authenticate` directly (outside `ExecuteRequestAsync`).OAuth1 signature generation no longer considers client.DefaultParameters when the authenticator is used directly, which can generate incorrect signatures for clients configured with default query/post parameters.
The library test suite calls authenticator.Authenticate(client, request) directly, so direct usage is part of supported workflows.
- src/RestSharp/Authenticators/OAuth/OAuth1Authenticator.cs[256-262]
- src/RestSharp/RestClient.Async.cs[104-117]
- test/RestSharp.Tests/Auth/OAuth1Tests.cs[43-50]
[reliability] Mutates request instance
Mutates request instance
`ExecuteRequestAsync` permanently mutates the caller-provided `RestRequest` by adding default parameters, which can make request reuse produce stale/incorrect defaults and can leak one client’s defaults into subsequent executions. This also makes behavior depend on whether the request has been executed before.ExecuteRequestAsync currently mutates the caller-provided RestRequest by injecting defaults, which can cause surprising/stale behavior when the same RestRequest instance is reused.
RestResponse stores the same RestRequest instance reference, so any mutation during execution becomes observable and persistent.
- src/RestSharp/RestClient.Async.cs[104-109]
- src/RestSharp/Request/RestRequest.cs[106-112]
- src/RestSharp/Response/RestResponseBase.cs[29-33]
| PR 2322 (2025-11-28) |
[possible issue] Fix incorrect method call example
✅ Fix incorrect method call example
Fix an incorrect PostJsonAsync method call example by adding the client instance and using the correct variable for the request body.
docs/versioned_docs/version-v112/intro.md [97-99]
-var response = await PostJsonAsync<AddressUpdateRequest, AddressUpdateResponse>(
- "address/update", request, cancellationToken
+var response = await client.PostJsonAsync<AddressUpdateRequest, AddressUpdateResponse>(
+ "address/update", updatedAddress, cancellationToken
);Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that the provided code example is non-functional as it's missing the client instance and uses an incorrect variable, and the proposed fix makes the example correct and usable.
[possible issue] Fix syntax error and type
✅ Fix syntax error and type
Fix a syntax error by replacing a comma with a semicolon and correct the type from Url to Uri in the RestClient configuration example.
docs/versioned_docs/version-v113/advanced/configuration.md [64-67]
var client = new RestClient(options => {
- options.BaseUrl = new Url("https://localhost:5000/api"),
+ options.BaseUrl = new Uri("https://localhost:5000/api");
options.DisableCharset = true
});Suggestion importance[1-10]: 6
__
Why: The suggestion correctly identifies a syntax error (a comma instead of a semicolon) and a type error (Url instead of Uri) in a documentation code example, improving its correctness and usability.
[possible issue] Fix invalid JSON string format
✅ Fix invalid JSON string format
Correct an invalid JSON string in a code example by enclosing the data key in double quotes as required by the JSON specification.
docs/versioned_docs/version-v113/usage/request.md [256-257]
-const json = "{ data: { foo: \"bar\" } }";
+const json = "{ \"data\": { \"foo\": \"bar\" } }";
request.AddStringBody(json, ContentType.Json);Suggestion importance[1-10]: 6
__
Why: The suggestion correctly identifies that the JSON string in the documentation example is invalid because a key is not quoted, which would cause issues for users copying the code.
[general] Correct a typo in package name
✅ Correct a typo in package name
Correct a typo in the RestSharp.Extensions.DependencyInjection package name mentioned in the changelog.
docs/versioned_docs/version-v113/changelog.md [29]
-* The new package `RestSharp.Extensions.DepdencyInjection` integrates RestSharp with Microsoft DI container and `IHttpClientFactory`.
+* The new package `RestSharp.Extensions.DependencyInjection` integrates RestSharp with Microsoft DI container and `IHttpClientFactory`.Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies and fixes a typo in a package name within the changelog, which is crucial for preventing user confusion and errors when trying to install the package.
| PR 2318 (2025-11-27) |
[general] Use a factory for client resolution
✅ Use a factory for client resolution
Register a factory (Func<string, IRestClient>) for IRestClient resolution to allow consumers to dynamically resolve named clients, rather than registering a single transient service.
src/RestSharp.Extensions.DependencyInjection/ServiceCollectionExtensions.cs [25-29]
-services.AddTransient<IRestClient>(sp => {
- var client = sp.GetRequiredService<IHttpClientFactory>().CreateClient(DefaultRestClient);
- return new RestClient(client, options);
- }
-);
+services.AddTransient(sp => {
+ var factory = sp.GetRequiredService<IHttpClientFactory>();
+ return (string name) => new RestClient(factory.CreateClient(name), options);
+});
+services.AddTransient<IRestClient>(sp => sp.GetRequiredService<Func<string, IRestClient>>()(DefaultRestClient));Suggestion importance[1-10]: 8
__
Why: The suggestion provides a robust and correct solution using a factory pattern (Func) to handle the registration and resolution of multiple named RestClient instances, which is a significant improvement over the PR's implementation.
[general] Allow registering multiple named clients
✅ Allow registering multiple named clients
Modify AddRestClient to accept a name parameter to support registering multiple named RestClient instances, instead of using a hardcoded name.
src/RestSharp.Extensions.DependencyInjection/ServiceCollectionExtensions.cs [8-30]
extension(IServiceCollection services) {
/// <summary>
/// Adds a RestClient to the service collection.
/// </summary>
+ /// <param name="name">The name of the client.</param>
/// <param name="options">The configuration options for the RestClient.</param>
[PublicAPI]
- public void AddRestClient(RestClientOptions options) {
+ public void AddRestClient(string name, RestClientOptions options) {
services
- .AddHttpClient(DefaultRestClient)
+ .AddHttpClient(name)
.ConfigureHttpClient(client => RestClient.ConfigureHttpClient(client, options))
.ConfigurePrimaryHttpMessageHandler(() => {
var handler = new HttpClientHandler();
RestClient.ConfigureHttpMessageHandler(handler, options);
return handler;
}
);
services.AddTransient<IRestClient>(sp => {
- var client = sp.GetRequiredService<IHttpClientFactory>().CreateClient(DefaultRestClient);
+ var client = sp.GetRequiredService<IHttpClientFactory>().CreateClient(name);
return new RestClient(client, options);
}
);
}Suggestion importance[1-10]: 5
__
Why: The suggestion correctly identifies a limitation with the hardcoded client name, but the proposed implementation is flawed as it would overwrite the IRestClient registration, making it impossible to resolve different named clients.