From ce9740b21dc436b376c70a57257af2ae8b0113fb Mon Sep 17 00:00:00 2001 From: Alexey Zimarev Date: Thu, 11 Sep 2025 20:01:44 +0200 Subject: [PATCH] Allow ignoring cookie exception --- src/RestSharp/Options/RestClientOptions.cs | 5 +++++ src/RestSharp/RestClient.Async.cs | 19 +++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/RestSharp/Options/RestClientOptions.cs b/src/RestSharp/Options/RestClientOptions.cs index 96ebf9df1..6c5af58f0 100644 --- a/src/RestSharp/Options/RestClientOptions.cs +++ b/src/RestSharp/Options/RestClientOptions.cs @@ -223,4 +223,9 @@ public RestClientOptions(string baseUrl) : this(new Uri(Ensure.NotEmptyString(ba /// Custom function to encode a string for use in a URL query. /// public Func EncodeQuery { get; set; } = (s, encoding) => s.UrlEncode(encoding)!; + + /// + /// Set to true to ignore invalid cookies returned by the remote server. Default is false. + /// + public bool IgnoreInvalidCookies { get; set; } } diff --git a/src/RestSharp/RestClient.Async.cs b/src/RestSharp/RestClient.Async.cs index 3bbb3f210..f8e731838 100644 --- a/src/RestSharp/RestClient.Async.cs +++ b/src/RestSharp/RestClient.Async.cs @@ -14,6 +14,8 @@ using RestSharp.Extensions; +// ReSharper disable PossiblyMistakenUseOfCancellationToken + namespace RestSharp; public partial class RestClient { @@ -145,21 +147,26 @@ async Task ExecuteRequestAsync(RestRequest request, CancellationTo // Parse all the cookies from the response and update the cookie jar with cookies if (responseMessage.Headers.TryGetValues(KnownHeaders.SetCookie, out var cookiesHeader)) { - // ReSharper disable once PossibleMultipleEnumeration - cookieContainer.AddCookies(url, cookiesHeader); - // ReSharper disable once PossibleMultipleEnumeration - Options.CookieContainer?.AddCookies(url, cookiesHeader); + try { + // ReSharper disable once PossibleMultipleEnumeration + cookieContainer.AddCookies(url, cookiesHeader); + // ReSharper disable once PossibleMultipleEnumeration + Options.CookieContainer?.AddCookies(url, cookiesHeader); + } + catch (CookieException) when (!Options.IgnoreInvalidCookies) { + throw; + } } } catch (Exception ex) { - return new HttpResponse(null, url, null, ex, timeoutCts.Token); + return new(null, url, null, ex, timeoutCts.Token); } #pragma warning disable CS0618 // Type or member is obsolete if (request.OnAfterRequest != null) await request.OnAfterRequest(responseMessage).ConfigureAwait(false); #pragma warning restore CS0618 // Type or member is obsolete await OnAfterHttpRequest(request, responseMessage, cancellationToken).ConfigureAwait(false); - return new HttpResponse(responseMessage, url, cookieContainer, null, timeoutCts.Token); + return new(responseMessage, url, cookieContainer, null, timeoutCts.Token); } static async ValueTask OnBeforeRequest(RestRequest request, CancellationToken cancellationToken) {