diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml
index 8c1faff17..9eeea5b38 100644
--- a/.github/workflows/pull-request.yml
+++ b/.github/workflows/pull-request.yml
@@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Upload
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v5
with:
name: Event File
path: ${{ github.event_path }}
@@ -28,21 +28,28 @@ jobs:
steps:
-
name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@v5
-
name: Setup .NET
- uses: actions/setup-dotnet@v4
+ uses: actions/setup-dotnet@v5
with:
dotnet-version: |
8.0.x
9.0.x
+ -
+ name: Setup .NET 10
+ uses: actions/setup-dotnet@v5
+ with:
+ dotnet-version: |
+ 10.0.x
+ dotnet-quality: 'preview'
-
name: Run tests
run: dotnet test -c Debug -f ${{ matrix.dotnet }}
-
name: Upload Test Results
if: always()
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v5
with:
name: Test Results Windows ${{ matrix.dotnet }}
path: |
@@ -59,21 +66,28 @@ jobs:
steps:
-
name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@v5
-
name: Setup .NET
- uses: actions/setup-dotnet@v4
+ uses: actions/setup-dotnet@v5
with:
dotnet-version: |
8.0.x
9.0.x
+ -
+ name: Setup .NET 10
+ uses: actions/setup-dotnet@v5
+ with:
+ dotnet-version: |
+ 10.0.x
+ dotnet-quality: 'preview'
-
name: Run tests
run: dotnet test -f ${{ matrix.dotnet }}
-
name: Upload Test Results
if: always()
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v5
with:
name: Test Results Ubuntu ${{ matrix.dotnet }}
path: |
diff --git a/Directory.Packages.props b/Directory.Packages.props
index ed1fd4b2e..9da81daba 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -2,16 +2,23 @@
true
-
- 8.0.3
+
+ 10.0.0-rc.2.25502.107
+ 10.0.0-rc.2.25502.107
-
- 9.0.0
+
+ 9.0.10
+
+
+ 8.0.21
+
+
+ 9.0.10
-
+
diff --git a/benchmarks/RestSharp.Benchmarks/Requests/AddObjectToRequestParametersBenchmarks.cs b/benchmarks/RestSharp.Benchmarks/Requests/AddObjectToRequestParametersBenchmarks.cs
index 072877d4b..355667196 100644
--- a/benchmarks/RestSharp.Benchmarks/Requests/AddObjectToRequestParametersBenchmarks.cs
+++ b/benchmarks/RestSharp.Benchmarks/Requests/AddObjectToRequestParametersBenchmarks.cs
@@ -20,7 +20,7 @@ public void GlobalSetup() {
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var dateTime = DateTime.Parse("01/01/2013 03:03:12");
- _data = new Data(@string, int.MaxValue, strings, ints, dateTime, strings);
+ _data = new(@string, int.MaxValue, strings, ints, dateTime, strings);
}
[Benchmark(Baseline = true)]
diff --git a/gen/SourceGenerator/Extensions.cs b/gen/SourceGenerator/Extensions.cs
index f529412a1..0e740eb6e 100644
--- a/gen/SourceGenerator/Extensions.cs
+++ b/gen/SourceGenerator/Extensions.cs
@@ -15,20 +15,22 @@
namespace SourceGenerator;
static class Extensions {
- public static IEnumerable FindClasses(this Compilation compilation, Func predicate)
- => compilation.SyntaxTrees
- .Select(tree => compilation.GetSemanticModel(tree))
- .SelectMany(model => model.SyntaxTree.GetRoot().DescendantNodes().OfType())
- .Where(predicate);
+ extension(Compilation compilation) {
+ public IEnumerable FindClasses(Func predicate)
+ => compilation.SyntaxTrees
+ .Select(tree => compilation.GetSemanticModel(tree))
+ .SelectMany(model => model.SyntaxTree.GetRoot().DescendantNodes().OfType())
+ .Where(predicate);
- public static IEnumerable FindAnnotatedClasses(this Compilation compilation, string attributeName, bool strict) {
- return compilation.FindClasses(
- syntax => syntax.AttributeLists.Any(list => list.Attributes.Any(CheckAttribute))
- );
+ public IEnumerable FindAnnotatedClasses(string attributeName, bool strict) {
+ return compilation.FindClasses(
+ syntax => syntax.AttributeLists.Any(list => list.Attributes.Any(CheckAttribute))
+ );
- bool CheckAttribute(AttributeSyntax attr) {
- var name = attr.Name.ToString();
- return strict ? name == attributeName : name.StartsWith(attributeName);
+ bool CheckAttribute(AttributeSyntax attr) {
+ var name = attr.Name.ToString();
+ return strict ? name == attributeName : name.StartsWith(attributeName);
+ }
}
}
diff --git a/src/Directory.Build.props b/src/Directory.Build.props
index 85288d985..549702c46 100644
--- a/src/Directory.Build.props
+++ b/src/Directory.Build.props
@@ -1,7 +1,7 @@
- netstandard2.0;net471;net48;net8.0;net9.0
+ netstandard2.0;net471;net48;net8.0;net9.0;net10.0
restsharp.png
Apache-2.0
https://restsharp.dev
diff --git a/src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs b/src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs
index f2ea1cc7c..54e82ab2a 100644
--- a/src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs
+++ b/src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs
@@ -18,7 +18,7 @@ public class CsvHelperSerializer(CsvConfiguration configuration) : IDeserializer
public ContentType ContentType { get; set; } = ContentType.Csv;
- public CsvHelperSerializer() : this(new CsvConfiguration(CultureInfo.InvariantCulture)) { }
+ public CsvHelperSerializer() : this(new(CultureInfo.InvariantCulture)) { }
public T? Deserialize(RestResponse response) {
try {
diff --git a/src/RestSharp.Serializers.CsvHelper/RestClientExtensions.cs b/src/RestSharp.Serializers.CsvHelper/RestClientExtensions.cs
index d71b6b38a..4d6456b76 100644
--- a/src/RestSharp.Serializers.CsvHelper/RestClientExtensions.cs
+++ b/src/RestSharp.Serializers.CsvHelper/RestClientExtensions.cs
@@ -4,8 +4,10 @@ namespace RestSharp.Serializers.CsvHelper;
[PublicAPI]
public static class RestClientExtensions {
- public static SerializerConfig UseCsvHelper(this SerializerConfig config) => config.UseSerializer();
+ extension(SerializerConfig config) {
+ public SerializerConfig UseCsvHelper() => config.UseSerializer();
- public static SerializerConfig UseCsvHelper(this SerializerConfig config, CsvConfiguration configuration)
- => config.UseSerializer(() => new CsvHelperSerializer(configuration));
+ public SerializerConfig UseCsvHelper(CsvConfiguration configuration)
+ => config.UseSerializer(() => new CsvHelperSerializer(configuration));
+ }
}
diff --git a/src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs b/src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs
index 2b41db918..d5ee33046 100644
--- a/src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs
+++ b/src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs
@@ -52,7 +52,7 @@ public class JsonNetSerializer : IRestSerializer, ISerializer, IDeserializer {
public string? Serialize(object? obj) {
if (obj == null) return null;
- using var buffer = _writerBuffer ??= new WriterBuffer(_serializer);
+ using var buffer = _writerBuffer ??= new(_serializer);
_serializer.Serialize(buffer.GetJsonTextWriter(), obj, obj.GetType());
diff --git a/src/RestSharp.Serializers.NewtonsoftJson/RestClientExtensions.cs b/src/RestSharp.Serializers.NewtonsoftJson/RestClientExtensions.cs
index f228ac07f..7f6e6ffec 100644
--- a/src/RestSharp.Serializers.NewtonsoftJson/RestClientExtensions.cs
+++ b/src/RestSharp.Serializers.NewtonsoftJson/RestClientExtensions.cs
@@ -16,19 +16,20 @@ namespace RestSharp.Serializers.NewtonsoftJson;
[PublicAPI]
public static class RestClientExtensions {
- ///
- /// Use Newtonsoft.Json serializer with default settings
- ///
///
- ///
- public static SerializerConfig UseNewtonsoftJson(this SerializerConfig config) => config.UseSerializer(() => new JsonNetSerializer());
+ extension(SerializerConfig config) {
+ ///
+ /// Use Newtonsoft.Json serializer with default settings
+ ///
+ ///
+ public SerializerConfig UseNewtonsoftJson() => config.UseSerializer(() => new JsonNetSerializer());
- ///
- /// Use Newtonsoft.Json serializer with custom settings
- ///
- ///
- /// Newtonsoft.Json serializer settings
- ///
- public static SerializerConfig UseNewtonsoftJson(this SerializerConfig config, JsonSerializerSettings settings)
- => config.UseSerializer(() => new JsonNetSerializer(settings));
+ ///
+ /// Use Newtonsoft.Json serializer with custom settings
+ ///
+ /// Newtonsoft.Json serializer settings
+ ///
+ public SerializerConfig UseNewtonsoftJson(JsonSerializerSettings settings)
+ => config.UseSerializer(() => new JsonNetSerializer(settings));
+ }
}
\ No newline at end of file
diff --git a/src/RestSharp.Serializers.NewtonsoftJson/WriterBuffer.cs b/src/RestSharp.Serializers.NewtonsoftJson/WriterBuffer.cs
index 7d77a5adc..a1505a869 100644
--- a/src/RestSharp.Serializers.NewtonsoftJson/WriterBuffer.cs
+++ b/src/RestSharp.Serializers.NewtonsoftJson/WriterBuffer.cs
@@ -13,7 +13,6 @@
// limitations under the License.
using System.Globalization;
-using System.Text;
namespace RestSharp.Serializers.NewtonsoftJson;
@@ -22,9 +21,9 @@ sealed class WriterBuffer : IDisposable {
readonly JsonTextWriter _jsonTextWriter;
public WriterBuffer(JsonSerializer jsonSerializer) {
- _stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture);
+ _stringWriter = new(new(256), CultureInfo.InvariantCulture);
- _jsonTextWriter = new JsonTextWriter(_stringWriter) {
+ _jsonTextWriter = new(_stringWriter) {
Formatting = jsonSerializer.Formatting, CloseOutput = false
};
}
diff --git a/src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs b/src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs
index fb1474d7b..598f446b5 100644
--- a/src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs
+++ b/src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs
@@ -27,12 +27,6 @@ namespace RestSharp.Serializers;
///
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false)]
public sealed class SerializeAsAttribute : Attribute {
- public SerializeAsAttribute() {
- NameStyle = NameStyle.AsIs;
- Index = int.MaxValue;
- Culture = CultureInfo.InvariantCulture;
- }
-
///
/// The name to use for the serialized element
///
@@ -51,17 +45,17 @@ public SerializeAsAttribute() {
///
/// The culture to use when serializing
///
- public CultureInfo Culture { get; set; }
+ public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture;
///
/// Transforms the casing of the name based on the selected value.
///
- public NameStyle NameStyle { get; set; }
+ public NameStyle NameStyle { get; set; } = NameStyle.AsIs;
///
/// The order to serialize the element. Default is int.MaxValue.
///
- public int Index { get; set; }
+ public int Index { get; set; } = int.MaxValue;
///
/// Called by the attribute when NameStyle is speficied
diff --git a/src/RestSharp.Serializers.Xml/XmlDeserializer.cs b/src/RestSharp.Serializers.Xml/XmlDeserializer.cs
index ee2fbf8af..99959b221 100644
--- a/src/RestSharp.Serializers.Xml/XmlDeserializer.cs
+++ b/src/RestSharp.Serializers.Xml/XmlDeserializer.cs
@@ -24,9 +24,7 @@
namespace RestSharp.Serializers.Xml;
public class XmlDeserializer : IXmlDeserializer, IWithRootElement, IWithDateFormat {
- public XmlDeserializer() => Culture = CultureInfo.InvariantCulture;
-
- public CultureInfo Culture { get; set; }
+ public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture;
public string? RootElement { get; set; }
@@ -75,7 +73,7 @@ static void RemoveNamespace(XDocument xdoc) {
a => a.IsNamespaceDeclaration
? null
: a.Name.Namespace != XNamespace.None
- ? new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value)
+ ? new(XNamespace.None.GetName(a.Name.LocalName), a.Value)
: a
)
);
@@ -227,7 +225,7 @@ protected virtual object Map(object x, XElement? root) {
else if (asType == typeof(Guid)) {
var raw = value.ToString();
- value = string.IsNullOrEmpty(raw) ? Guid.Empty : new Guid(value.ToString()!);
+ value = string.IsNullOrEmpty(raw) ? Guid.Empty : new(value.ToString()!);
prop.SetValue(x, value, null);
}
diff --git a/src/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs b/src/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs
index aef613233..3b6d557b0 100644
--- a/src/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs
+++ b/src/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs
@@ -17,13 +17,15 @@
namespace RestSharp.Authenticators.OAuth.Extensions;
static class StringExtensions {
- public static bool EqualsIgnoreCase(this string left, string right) => string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase);
+ extension(string left) {
+ public bool EqualsIgnoreCase(string right) => string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase);
- public static string Then(this string input, string value) => string.Concat(input, value);
+ public string Then(string value) => string.Concat(left, value);
- public static Uri AsUri(this string value) => new(value);
+ public Uri AsUri() => new(left);
- public static byte[] GetBytes(this string input) => Encoding.UTF8.GetBytes(input);
+ public byte[] GetBytes() => Encoding.UTF8.GetBytes(left);
- public static string PercentEncode(this string s) => string.Join("", s.GetBytes().Select(x => $"%{x:X2}"));
+ public string PercentEncode() => string.Join("", left.GetBytes().Select(x => $"%{x:X2}"));
+ }
}
\ No newline at end of file
diff --git a/src/RestSharp/Authenticators/OAuth/OAuthTools.cs b/src/RestSharp/Authenticators/OAuth/OAuthTools.cs
index 4c70eab8e..1c4f7ab92 100644
--- a/src/RestSharp/Authenticators/OAuth/OAuthTools.cs
+++ b/src/RestSharp/Authenticators/OAuth/OAuthTools.cs
@@ -44,7 +44,7 @@ static OAuthTools() {
var bytes = new byte[4];
Rng.GetBytes(bytes);
- Random = new Random(BitConverter.ToInt32(bytes, 0));
+ Random = new(BitConverter.ToInt32(bytes, 0));
}
///
@@ -60,7 +60,7 @@ public static string GetNonce() {
for (var i = 0; i < nonce.Length; i++) nonce[i] = chars[Random.Next(0, chars.Length)];
}
- return new string(nonce);
+ return new(nonce);
}
///
diff --git a/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs b/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs
index 894bb24f9..d1818ec55 100644
--- a/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs
+++ b/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs
@@ -62,7 +62,7 @@ public OAuthParameters BuildRequestTokenSignature(string method, WebPairCollecti
var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters);
- return new OAuthParameters {
+ return new() {
Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret),
Parameters = authParameters
};
@@ -91,7 +91,7 @@ public OAuthParameters BuildAccessTokenSignature(string method, WebPairCollectio
var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters);
- return new OAuthParameters {
+ return new() {
Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret),
Parameters = authParameters
};
@@ -120,7 +120,7 @@ public OAuthParameters BuildClientAuthAccessTokenSignature(string method, WebPai
var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters);
- return new OAuthParameters {
+ return new() {
Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret),
Parameters = authParameters
};
@@ -133,7 +133,7 @@ public OAuthParameters BuildProtectedResourceSignature(string method, WebPairCol
allParameters.AddRange(parameters);
// Include url parameters in query pool
- var uri = new Uri(Ensure.NotEmptyString(RequestUrl, nameof(RequestUrl)));
+ var uri = new Uri(Ensure.NotEmptyString(RequestUrl, nameof(RequestUrl)));
var urlParameters = HttpUtility.ParseQueryString(uri.Query);
allParameters.AddRange(urlParameters.AllKeys.Select(x => new WebPair(x!, urlParameters[x]!)));
@@ -146,7 +146,7 @@ public OAuthParameters BuildProtectedResourceSignature(string method, WebPairCol
var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters);
- return new OAuthParameters {
+ return new() {
Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret),
Parameters = authParameters
};
@@ -167,14 +167,14 @@ WebPairCollection GenerateAuthParameters(string timestamp, string nonce)
WebPairCollection GenerateXAuthParameters(string timestamp, string nonce)
=> [
- new WebPair("x_auth_username", Ensure.NotNull(ClientUsername, nameof(ClientUsername))),
- new WebPair("x_auth_password", Ensure.NotNull(ClientPassword, nameof(ClientPassword))),
- new WebPair("x_auth_mode", "client_auth"),
- new WebPair("oauth_consumer_key", Ensure.NotNull(ConsumerKey, nameof(ConsumerKey)), true),
- new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()),
- new WebPair("oauth_timestamp", timestamp),
- new WebPair("oauth_nonce", nonce),
- new WebPair("oauth_version", Version ?? "1.0")
+ new("x_auth_username", Ensure.NotNull(ClientUsername, nameof(ClientUsername))),
+ new("x_auth_password", Ensure.NotNull(ClientPassword, nameof(ClientPassword))),
+ new("x_auth_mode", "client_auth"),
+ new("oauth_consumer_key", Ensure.NotNull(ConsumerKey, nameof(ConsumerKey)), true),
+ new("oauth_signature_method", SignatureMethod.ToRequestValue()),
+ new("oauth_timestamp", timestamp),
+ new("oauth_nonce", nonce),
+ new("oauth_version", Version ?? "1.0")
];
internal class OAuthParameters {
diff --git a/src/RestSharp/Authenticators/OAuth/WebPairCollection.cs b/src/RestSharp/Authenticators/OAuth/WebPairCollection.cs
index 29134488f..550d0e7d6 100644
--- a/src/RestSharp/Authenticators/OAuth/WebPairCollection.cs
+++ b/src/RestSharp/Authenticators/OAuth/WebPairCollection.cs
@@ -27,11 +27,11 @@ class WebPairCollection : IList {
public void AddRange(IEnumerable collection) => AddCollection(collection);
- public void Add(string name, string value) => Add(new WebPair(name, value));
+ public void Add(string name, string value) => Add(new(name, value));
public WebPairCollection AddNotEmpty(string name, string? value, bool encode = false) {
if (value != null)
- Add(new WebPair(name, value, encode));
+ Add(new(name, value, encode));
return this;
}
diff --git a/src/RestSharp/BuildUriExtensions.cs b/src/RestSharp/BuildUriExtensions.cs
index ba6676230..6bf976244 100644
--- a/src/RestSharp/BuildUriExtensions.cs
+++ b/src/RestSharp/BuildUriExtensions.cs
@@ -16,71 +16,71 @@
namespace RestSharp;
public static class BuildUriExtensions {
- ///
- /// Builds the URI for the request
- ///
/// Client instance
- /// Request instance
- ///
- public static Uri BuildUri(this IRestClient client, RestRequest request) {
- DoBuildUriValidations(client, request);
+ extension(IRestClient client) {
+ ///
+ /// Builds the URI for the request
+ ///
+ /// Request instance
+ ///
+ public Uri BuildUri(RestRequest request) {
+ DoBuildUriValidations(client, request);
- var (uri, resource) = client.Options.BaseUrl.GetUrlSegmentParamsValues(
- request.Resource,
- client.Options.Encode,
- request.Parameters,
- client.DefaultParameters
- );
- var mergedUri = uri.MergeBaseUrlAndResource(resource);
- var query = client.GetRequestQuery(request);
- return mergedUri.AddQueryString(query);
- }
+ var (uri, resource) = client.Options.BaseUrl.GetUrlSegmentParamsValues(
+ request.Resource,
+ client.Options.Encode,
+ request.Parameters,
+ client.DefaultParameters
+ );
+ var mergedUri = uri.MergeBaseUrlAndResource(resource);
+ var query = client.GetRequestQuery(request);
+ return mergedUri.AddQueryString(query);
+ }
- ///
- /// Builds the URI for the request without query parameters.
- ///
- /// Client instance
- /// Request instance
- ///
- public static Uri BuildUriWithoutQueryParameters(this IRestClient client, RestRequest request) {
- DoBuildUriValidations(client, request);
+ ///
+ /// Builds the URI for the request without query parameters.
+ ///
+ /// Request instance
+ ///
+ public Uri BuildUriWithoutQueryParameters(RestRequest request) {
+ DoBuildUriValidations(client, request);
- var (uri, resource) = client.Options.BaseUrl.GetUrlSegmentParamsValues(
- request.Resource,
- client.Options.Encode,
- request.Parameters,
- client.DefaultParameters
- );
- return uri.MergeBaseUrlAndResource(resource);
- }
+ var (uri, resource) = client.Options.BaseUrl.GetUrlSegmentParamsValues(
+ request.Resource,
+ client.Options.Encode,
+ request.Parameters,
+ client.DefaultParameters
+ );
+ return uri.MergeBaseUrlAndResource(resource);
+ }
- ///
- /// Gets the query string for the request.
- ///
- /// Client instance
- /// Request instance
- ///
- [PublicAPI]
- public static string? GetRequestQuery(this IRestClient client, RestRequest request) {
- var parametersCollections = new ParametersCollection[] { request.Parameters, client.DefaultParameters };
+ ///
+ /// Gets the query string for the request.
+ ///
+ /// Request instance
+ ///
+ [PublicAPI]
+ public string? GetRequestQuery(RestRequest request) {
+ var parametersCollections = new ParametersCollection[] { request.Parameters, client.DefaultParameters };
- var parameters = parametersCollections.SelectMany(x => x.GetQueryParameters(request.Method)).ToList();
+ var parameters = parametersCollections.SelectMany(x => x.GetQueryParameters(request.Method)).ToList();
- return parameters.Count == 0 ? null : string.Join("&", parameters.Select(EncodeParameter).ToArray());
+ return parameters.Count == 0 ? null : string.Join("&", parameters.Select(EncodeParameter).ToArray());
- string GetString(string name, string? value, Func? encode) {
- var val = encode != null && value != null ? encode(value) : value;
- return val == null ? name : $"{name}={val}";
- }
+ string GetString(string name, string? value, Func? encode) {
+ var val = encode != null && value != null ? encode(value) : value;
+ return val == null ? name : $"{name}={val}";
+ }
- string EncodeParameter(Parameter parameter)
- => !parameter.Encode
- ? GetString(parameter.Name!, parameter.Value?.ToString(), null)
- : GetString(
- client.Options.EncodeQuery(parameter.Name!, client.Options.Encoding),
- parameter.Value?.ToString(),
- x => client.Options.EncodeQuery(x, client.Options.Encoding)
- );
+ string EncodeParameter(Parameter parameter)
+ => !parameter.Encode
+ ? GetString(parameter.Name!, parameter.Value?.ToString(), null)
+ : GetString(
+ client.Options.EncodeQuery(parameter.Name!, client.Options.Encoding),
+ parameter.Value?.ToString(),
+ x => client.Options.EncodeQuery(x, client.Options.Encoding)
+ );
+ }
}
static void DoBuildUriValidations(IRestClient client, RestRequest request) {
diff --git a/src/RestSharp/ContentType.cs b/src/RestSharp/ContentType.cs
index 6425dec89..8f8d70554 100644
--- a/src/RestSharp/ContentType.cs
+++ b/src/RestSharp/ContentType.cs
@@ -41,7 +41,7 @@ public class ContentType : IEquatable {
public override string ToString() => Value;
- public static implicit operator ContentType(string? contentType) => contentType == null ? Undefined : new ContentType(contentType);
+ public static implicit operator ContentType(string? contentType) => contentType == null ? Undefined : new(contentType);
public static implicit operator string(ContentType contentType) => contentType.Value;
diff --git a/src/RestSharp/Extensions/StringExtensions.cs b/src/RestSharp/Extensions/StringExtensions.cs
index 6980d3a45..637177a67 100644
--- a/src/RestSharp/Extensions/StringExtensions.cs
+++ b/src/RestSharp/Extensions/StringExtensions.cs
@@ -36,114 +36,117 @@ static partial class StringExtensions {
static readonly Regex AddSpacesRegex2 = AddSpaces2();
static readonly Regex AddSpacesRegex3 = AddSpaces3();
- internal static string UrlDecode(this string input) => HttpUtility.UrlDecode(input);
+ extension(string input) {
+ internal string UrlDecode() => HttpUtility.UrlDecode(input);
- ///
- /// Uses Uri.EscapeDataString() based on recommendations on MSDN
- /// http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx
- ///
- internal static string UrlEncode(this string input) {
- const int maxLength = 32766;
+ ///
+ /// Uses Uri.EscapeDataString() based on recommendations on MSDN
+ /// http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx
+ ///
+ internal string UrlEncode() {
+ const int maxLength = 32766;
- if (input == null) throw new ArgumentNullException(nameof(input));
+ if (input == null) throw new ArgumentNullException(nameof(input));
- if (input.Length <= maxLength) return Uri.EscapeDataString(input);
+ if (input.Length <= maxLength) return Uri.EscapeDataString(input);
- var sb = new StringBuilder(input.Length * 2);
- var index = 0;
+ var sb = new StringBuilder(input.Length * 2);
+ var index = 0;
- while (index < input.Length) {
- var length = Math.Min(input.Length - index, maxLength);
+ while (index < input.Length) {
+ var length = Math.Min(input.Length - index, maxLength);
- while (CharUnicodeInfo.GetUnicodeCategory(input[index + length - 1]) == UnicodeCategory.Surrogate) {
- length--;
- }
+ while (CharUnicodeInfo.GetUnicodeCategory(input[index + length - 1]) == UnicodeCategory.Surrogate) {
+ length--;
+ }
- var subString = input.Substring(index, length);
+ var subString = input.Substring(index, length);
- sb.Append(Uri.EscapeDataString(subString));
- index += subString.Length;
- }
+ sb.Append(Uri.EscapeDataString(subString));
+ index += subString.Length;
+ }
- return sb.ToString();
- }
+ return sb.ToString();
+ }
- internal static string? UrlEncode(this string? input, Encoding encoding) {
- var encoded = HttpUtility.UrlEncode(input, encoding);
- return encoded?.Replace("+", "%20");
+ internal string? UrlEncode(Encoding encoding) {
+ var encoded = HttpUtility.UrlEncode(input, encoding);
+ return encoded?.Replace("+", "%20");
+ }
}
- internal static string RemoveUnderscoresAndDashes(this string input) => input.Replace("_", "").Replace("-", "");
+ extension(string input) {
+ internal string RemoveUnderscoresAndDashes() => input.Replace("_", "").Replace("-", "");
- internal static string ToPascalCase(this string lowercaseAndUnderscoredWord, CultureInfo culture)
- => ToPascalCase(lowercaseAndUnderscoredWord, true, culture);
+ internal string ToPascalCase(CultureInfo culture) => ToPascalCase(input, true, culture);
- internal static string ToPascalCase(this string text, bool removeUnderscores, CultureInfo culture) {
- if (string.IsNullOrEmpty(text)) return text;
+ internal string ToPascalCase(bool removeUnderscores, CultureInfo culture) {
+ if (string.IsNullOrEmpty(input)) return input;
- text = text.Replace('_', ' ');
+ input = input.Replace('_', ' ');
- var joinString = removeUnderscores ? string.Empty : "_";
- var words = text.Split(' ');
+ var joinString = removeUnderscores ? string.Empty : "_";
+ var words = input.Split(' ');
- return words
- .Where(x => x.Length > 0)
- .Select(CaseWord)
- .JoinToString(joinString);
+ return words
+ .Where(x => x.Length > 0)
+ .Select(CaseWord)
+ .JoinToString(joinString);
- string CaseWord(string word) {
- var restOfWord = word[1..];
- var firstChar = char.ToUpper(word[0], culture);
+ string CaseWord(string word) {
+ var restOfWord = word[1..];
+ var firstChar = char.ToUpper(word[0], culture);
- if (restOfWord.IsUpperCase()) restOfWord = restOfWord.ToLower(culture);
+ if (restOfWord.IsUpperCase()) restOfWord = restOfWord.ToLower(culture);
- return string.Concat(firstChar, restOfWord);
+ return string.Concat(firstChar, restOfWord);
+ }
}
- }
- internal static string ToCamelCase(this string lowercaseAndUnderscoredWord, CultureInfo culture)
- => MakeInitialLowerCase(ToPascalCase(lowercaseAndUnderscoredWord, culture), culture);
+ internal string ToCamelCase(CultureInfo culture)
+ => MakeInitialLowerCase(ToPascalCase(input, culture), culture);
- internal static IEnumerable GetNameVariants(this string name, CultureInfo culture) {
- if (string.IsNullOrEmpty(name)) yield break;
+ internal IEnumerable GetNameVariants(CultureInfo culture) {
+ if (string.IsNullOrEmpty(input)) yield break;
- yield return name;
+ yield return input;
- // try camel cased name
- yield return name.ToCamelCase(culture);
+ // try camel cased name
+ yield return input.ToCamelCase(culture);
- // try lower cased name
- yield return name.ToLower(culture);
+ // try lower cased name
+ yield return input.ToLower(culture);
- // try name with underscores
- yield return name.AddUnderscores();
+ // try name with underscores
+ yield return input.AddUnderscores();
- // try name with underscores with lower case
- yield return name.AddUnderscores().ToLower(culture);
+ // try name with underscores with lower case
+ yield return input.AddUnderscores().ToLower(culture);
- // try name with dashes
- yield return name.AddDashes();
+ // try name with dashes
+ yield return input.AddDashes();
- // try name with dashes with lower case
- yield return name.AddDashes().ToLower(culture);
+ // try name with dashes with lower case
+ yield return input.AddDashes().ToLower(culture);
- // try name with underscore prefix
- yield return name.AddUnderscorePrefix();
+ // try name with underscore prefix
+ yield return input.AddUnderscorePrefix();
- // try name with proper camel case
- yield return name.AddUnderscores().ToCamelCase(culture);
+ // try name with proper camel case
+ yield return input.AddUnderscores().ToCamelCase(culture);
- // try name with underscore prefix, using proper camel case
- yield return name.ToCamelCase(culture).AddUnderscorePrefix();
+ // try name with underscore prefix, using proper camel case
+ yield return input.ToCamelCase(culture).AddUnderscorePrefix();
- // try name with underscore prefix, using camel case
- yield return name.AddUnderscores().ToCamelCase(culture).AddUnderscorePrefix();
+ // try name with underscore prefix, using camel case
+ yield return input.AddUnderscores().ToCamelCase(culture).AddUnderscorePrefix();
- // try name with spaces
- yield return name.AddSpaces();
+ // try name with spaces
+ yield return input.AddSpaces();
- // try name with spaces with lower case
- yield return name.AddSpaces().ToLower(culture);
+ // try name with spaces with lower case
+ yield return input.AddSpaces().ToLower(culture);
+ }
}
internal static bool IsEmpty([NotNullWhen(false)] this string? value) => string.IsNullOrWhiteSpace(value);
@@ -152,38 +155,40 @@ internal static IEnumerable GetNameVariants(this string name, CultureInf
internal static string JoinToString(this IEnumerable strings, string separator) => string.Join(separator, strings);
- static string MakeInitialLowerCase(this string word, CultureInfo culture) => string.Concat(word[..1].ToLower(culture), word[1..]);
-
- static string AddUnderscores(this string pascalCasedWord)
- => AddUnderscoresRegex1.Replace(
- AddUnderscoresRegex2.Replace(
- AddUnderscoresRegex3.Replace(pascalCasedWord, "$1_$2"),
- "$1_$2"
- ),
- "_"
- );
-
- static string AddDashes(this string pascalCasedWord)
- => AddDashesRegex1.Replace(
- AddDashesRegex2.Replace(
- AddDashesRegex3.Replace(pascalCasedWord, "$1-$2"),
- "$1-$2"
- ),
- "-"
- );
-
- static bool IsUpperCase(this string inputString) => IsUpperCaseRegex.IsMatch(inputString);
-
- static string AddUnderscorePrefix(this string pascalCasedWord) => $"_{pascalCasedWord}";
-
- static string AddSpaces(this string pascalCasedWord)
- => AddSpacesRegex1.Replace(
- AddSpacesRegex2.Replace(
- AddSpacesRegex3.Replace(pascalCasedWord, "$1 $2"),
- "$1 $2"
- ),
- " "
- );
+ extension(string word) {
+ string MakeInitialLowerCase(CultureInfo culture) => string.Concat(word[..1].ToLower(culture), word[1..]);
+
+ string AddUnderscores()
+ => AddUnderscoresRegex1.Replace(
+ AddUnderscoresRegex2.Replace(
+ AddUnderscoresRegex3.Replace(word, "$1_$2"),
+ "$1_$2"
+ ),
+ "_"
+ );
+
+ string AddDashes()
+ => AddDashesRegex1.Replace(
+ AddDashesRegex2.Replace(
+ AddDashesRegex3.Replace(word, "$1-$2"),
+ "$1-$2"
+ ),
+ "-"
+ );
+
+ bool IsUpperCase() => IsUpperCaseRegex.IsMatch(word);
+
+ string AddUnderscorePrefix() => $"_{word}";
+
+ string AddSpaces()
+ => AddSpacesRegex1.Replace(
+ AddSpacesRegex2.Replace(
+ AddSpacesRegex3.Replace(word, "$1 $2"),
+ "$1 $2"
+ ),
+ " "
+ );
+ }
const string RIsUpperCase = "^[A-Z]+$";
const string RAddUnderscore1 = @"[-\s]";
diff --git a/src/RestSharp/Parameters/FileParameter.cs b/src/RestSharp/Parameters/FileParameter.cs
index dfb4d25d1..d490d9fd3 100644
--- a/src/RestSharp/Parameters/FileParameter.cs
+++ b/src/RestSharp/Parameters/FileParameter.cs
@@ -65,7 +65,7 @@ public static FileParameter Create(
ContentType? contentType = null,
FileParameterOptions? options = null
) {
- return new FileParameter(name, filename, GetFile, contentType, options ?? new FileParameterOptions());
+ return new(name, filename, GetFile, contentType, options ?? new FileParameterOptions());
Stream GetFile() {
var stream = new MemoryStream();
@@ -105,7 +105,7 @@ public static FileParameter FromFile(
var fileName = Path.GetFileName(fullPath);
var parameterName = name ?? fileName;
- return new FileParameter(parameterName, fileName, GetFile, contentType, options ?? new FileParameterOptions());
+ return new(parameterName, fileName, GetFile, contentType, options ?? new FileParameterOptions());
Stream GetFile() => File.OpenRead(fullPath);
}
diff --git a/src/RestSharp/Parameters/ObjectParser.cs b/src/RestSharp/Parameters/ObjectParser.cs
index db9a03d9d..3f3464d97 100644
--- a/src/RestSharp/Parameters/ObjectParser.cs
+++ b/src/RestSharp/Parameters/ObjectParser.cs
@@ -42,7 +42,7 @@ ParsedParameter GetValue(PropertyInfo propertyInfo, object? value) {
var attribute = propertyInfo.GetCustomAttribute();
var name = attribute?.Name ?? propertyInfo.Name;
var val = ParseValue(attribute?.Format, value);
- return new ParsedParameter(name, val, attribute?.Encode ?? true);
+ return new(name, val, attribute?.Encode ?? true);
}
IEnumerable GetArray(PropertyInfo propertyInfo, object? value) {
@@ -54,7 +54,7 @@ IEnumerable GetArray(PropertyInfo propertyInfo, object? value)
var queryType = attribute?.ArrayQueryType ?? RequestArrayQueryType.CommaSeparated;
var encode = attribute?.Encode ?? true;
- if (array.Length <= 0 || elementType == null) return new ParsedParameter[] { new(name, null, encode) };
+ if (array.Length <= 0 || elementType == null) return [new(name, null, encode)];
// convert the array to an array of strings
var values = array
@@ -62,7 +62,7 @@ IEnumerable GetArray(PropertyInfo propertyInfo, object? value)
.Select(item => ParseValue(attribute?.Format, item));
return queryType switch {
- RequestArrayQueryType.CommaSeparated => new[] { new ParsedParameter(name, string.Join(",", values), encode) },
+ RequestArrayQueryType.CommaSeparated => [new(name, string.Join(",", values), encode)],
RequestArrayQueryType.ArrayParameters => values.Select(x => new ParsedParameter($"{name}[]", x, encode)),
_ => throw new ArgumentOutOfRangeException()
};
diff --git a/src/RestSharp/Parameters/ParametersCollectionExtensions.cs b/src/RestSharp/Parameters/ParametersCollectionExtensions.cs
index 83b6eefa6..7be33e8b9 100644
--- a/src/RestSharp/Parameters/ParametersCollectionExtensions.cs
+++ b/src/RestSharp/Parameters/ParametersCollectionExtensions.cs
@@ -16,17 +16,19 @@
namespace RestSharp;
static class ParametersCollectionExtensions {
- internal static IEnumerable GetQueryParameters(this ParametersCollection parameters, Method method) {
- Func condition =
- !IsPost(method)
- ? p => p.Type is ParameterType.GetOrPost or ParameterType.QueryString
- : p => p.Type is ParameterType.QueryString;
+ extension(ParametersCollection parameters) {
+ internal IEnumerable GetQueryParameters(Method method) {
+ Func condition =
+ !IsPost(method)
+ ? p => p.Type is ParameterType.GetOrPost or ParameterType.QueryString
+ : p => p.Type is ParameterType.QueryString;
- return parameters.Where(p => condition(p));
- }
+ return parameters.Where(p => condition(p));
+ }
- internal static IEnumerable GetContentParameters(this ParametersCollection parameters, Method method)
- => IsPost(method) ? parameters.GetParameters() : [];
+ internal IEnumerable GetContentParameters(Method method)
+ => IsPost(method) ? parameters.GetParameters() : [];
+ }
static bool IsPost(Method method) => method is Method.Post or Method.Put or Method.Patch;
}
diff --git a/src/RestSharp/Polyfills/Index.cs b/src/RestSharp/Polyfills/Index.cs
index 6599a38fa..972b842e6 100644
--- a/src/RestSharp/Polyfills/Index.cs
+++ b/src/RestSharp/Polyfills/Index.cs
@@ -49,24 +49,12 @@ public Index(int value, bool fromEnd = false) {
/// Create an Index from the start at the position indicated by the value.
/// The index value from the start.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static Index FromStart(int value) {
- if (value < 0) {
- throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative");
- }
-
- return new Index(value);
- }
+ public static Index FromStart(int value) => value < 0 ? throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative") : new Index(value);
/// Create an Index from the end at the position indicated by the value.
/// The index value from the end.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static Index FromEnd(int value) {
- if (value < 0) {
- throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative");
- }
-
- return new Index(~value);
- }
+ public static Index FromEnd(int value) => value < 0 ? throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative") : new Index(~value);
/// Returns the index value.
public int Value {
diff --git a/src/RestSharp/Polyfills/Range.cs b/src/RestSharp/Polyfills/Range.cs
index 15a45b036..49634660e 100644
--- a/src/RestSharp/Polyfills/Range.cs
+++ b/src/RestSharp/Polyfills/Range.cs
@@ -47,16 +47,16 @@ public override bool Equals(object? value)
public override int GetHashCode() => Start.GetHashCode() * 31 + End.GetHashCode();
/// Converts the value of the current Range object to its equivalent string representation.
- public override string ToString() => Start + ".." + End;
+ public override string ToString() => $"{Start}..{End}";
/// Create a Range object starting from start index to the end of the collection.
- public static Range StartAt(Index start) => new Range(start, Index.End);
+ public static Range StartAt(Index start) => new(start, Index.End);
/// Create a Range object starting from first element in the collection to the end Index.
- public static Range EndAt(Index end) => new Range(Index.Start, end);
+ public static Range EndAt(Index end) => new(Index.Start, end);
/// Create a Range object starting from first element to the end.
- public static Range All => new Range(Index.Start, Index.End);
+ public static Range All => new(Index.Start, Index.End);
/// Calculate the start offset and length of range object using a collection length.
/// The length of the collection that the range will be used with. length has to be a positive value.
diff --git a/src/RestSharp/Request/BodyExtensions.cs b/src/RestSharp/Request/BodyExtensions.cs
index 1c6a592e9..958f97289 100644
--- a/src/RestSharp/Request/BodyExtensions.cs
+++ b/src/RestSharp/Request/BodyExtensions.cs
@@ -18,10 +18,12 @@ namespace RestSharp;
using System.Diagnostics.CodeAnalysis;
static class BodyExtensions {
- public static bool TryGetBodyParameter(this RestRequest request, [NotNullWhen(true)] out BodyParameter? bodyParameter) {
- bodyParameter = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody) as BodyParameter;
- return bodyParameter != null;
- }
+ extension(RestRequest request) {
+ public bool TryGetBodyParameter([NotNullWhen(true)] out BodyParameter? bodyParameter) {
+ bodyParameter = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody) as BodyParameter;
+ return bodyParameter != null;
+ }
- public static bool HasFiles(this RestRequest request) => request.Files.Count > 0;
+ public bool HasFiles() => request.Files.Count > 0;
+ }
}
diff --git a/src/RestSharp/Request/PropertyCache.Populator.RequestProperty.cs b/src/RestSharp/Request/PropertyCache.Populator.RequestProperty.cs
index 7fce7d197..0c6f59814 100644
--- a/src/RestSharp/Request/PropertyCache.Populator.RequestProperty.cs
+++ b/src/RestSharp/Request/PropertyCache.Populator.RequestProperty.cs
@@ -58,7 +58,7 @@ internal static RequestProperty From(PropertyInfo property) {
var propertyName = requestPropertyAttribute.Name ?? property.Name;
- return new RequestProperty(
+ return new(
propertyName,
requestPropertyAttribute.Format,
requestPropertyAttribute.ArrayQueryType,
diff --git a/src/RestSharp/Request/PropertyCache.Populator.cs b/src/RestSharp/Request/PropertyCache.Populator.cs
index 5074122bb..4057ac999 100644
--- a/src/RestSharp/Request/PropertyCache.Populator.cs
+++ b/src/RestSharp/Request/PropertyCache.Populator.cs
@@ -74,7 +74,7 @@ internal static Populator From(PropertyInfo property) {
var populate = GetPopulate(getObject, property);
- return new Populator(property.Name, populate);
+ return new(property.Name, populate);
}
static Action> GetPopulate(Func getFormattable, RequestProperty requestProperty)
diff --git a/src/RestSharp/Request/RequestContent.cs b/src/RestSharp/Request/RequestContent.cs
index 997cfd177..03af0bdcf 100644
--- a/src/RestSharp/Request/RequestContent.cs
+++ b/src/RestSharp/Request/RequestContent.cs
@@ -74,7 +74,7 @@ StreamContent ToStreamContent(FileParameter fileParameter) {
var dispositionHeader = fileParameter.Options.DisableFilenameEncoding
? ContentDispositionHeaderValue.Parse($"form-data; name=\"{fileParameter.Name}\"; filename=\"{fileParameter.FileName}\"")
- : new ContentDispositionHeaderValue("form-data") { Name = $"\"{fileParameter.Name}\"", FileName = $"\"{fileParameter.FileName}\"" };
+ : new("form-data") { Name = $"\"{fileParameter.Name}\"", FileName = $"\"{fileParameter.FileName}\"" };
if (!fileParameter.Options.DisableFilenameStar) dispositionHeader.FileNameStar = fileParameter.FileName;
streamContent.Headers.ContentDisposition = dispositionHeader;
@@ -125,7 +125,7 @@ MultipartFormDataContent CreateMultipartFormDataContent() {
var boundary = GetOrSetFormBoundary();
var mpContent = new MultipartFormDataContent(boundary);
var contentType = new MediaTypeHeaderValue("multipart/form-data");
- contentType.Parameters.Add(new NameValueHeaderValue(nameof(boundary), GetBoundary(boundary, request.MultipartFormQuoteBoundary)));
+ contentType.Parameters.Add(new(nameof(boundary), GetBoundary(boundary, request.MultipartFormQuoteBoundary)));
mpContent.Headers.ContentType = contentType;
return mpContent;
}
diff --git a/src/RestSharp/Request/RestRequest.cs b/src/RestSharp/Request/RestRequest.cs
index eaad89972..786f11304 100644
--- a/src/RestSharp/Request/RestRequest.cs
+++ b/src/RestSharp/Request/RestRequest.cs
@@ -26,9 +26,6 @@ namespace RestSharp;
/// Container for data used to make requests
///
public class RestRequest {
- Func? _advancedResponseHandler;
- Func? _responseWriter;
-
///
/// Default constructor
///
@@ -212,13 +209,13 @@ public RestRequest(Uri resource, Method method = Method.Get)
/// Set this to write response to Stream rather than reading into memory.
///
public Func? ResponseWriter {
- get => _responseWriter;
+ get;
set {
if (AdvancedResponseWriter != null) {
throw new ArgumentException("AdvancedResponseWriter is not null. Only one response writer can be used.");
}
- _responseWriter = value;
+ field = value;
}
}
@@ -226,13 +223,13 @@ public RestRequest(Uri resource, Method method = Method.Get)
/// Set this to handle the response stream yourself, based on the response details
///
public Func? AdvancedResponseWriter {
- get => _advancedResponseHandler;
+ get;
set {
if (ResponseWriter != null) {
throw new ArgumentException("ResponseWriter is not null. Only one response writer can be used.");
}
- _advancedResponseHandler = value;
+ field = value;
}
}
diff --git a/src/RestSharp/Request/RestRequestExtensions.Body.cs b/src/RestSharp/Request/RestRequestExtensions.Body.cs
index dad5d006a..39e0a1cde 100644
--- a/src/RestSharp/Request/RestRequestExtensions.Body.cs
+++ b/src/RestSharp/Request/RestRequestExtensions.Body.cs
@@ -15,106 +15,104 @@
namespace RestSharp;
public static partial class RestRequestExtensions {
- ///
- /// Adds a body parameter to the request
- ///
/// Request instance
- /// Object to be used as the request body, or string for plain content
- /// Optional: content type
- ///
- /// Thrown if request body type cannot be resolved
- /// This method will try to figure out the right content type based on the request data format and the provided content type
- public static RestRequest AddBody(this RestRequest request, object obj, ContentType? contentType = null) {
- if (contentType == null) {
- return request.RequestFormat switch {
- DataFormat.Json => request.AddJsonBody(obj, contentType),
- DataFormat.Xml => request.AddXmlBody(obj, contentType),
- DataFormat.Binary => request.AddParameter(new BodyParameter("", obj, ContentType.Binary)),
- _ => request.AddParameter(new BodyParameter("", obj.ToString()!, ContentType.Plain))
- };
+ extension(RestRequest request) {
+ ///
+ /// Adds a body parameter to the request
+ ///
+ /// Object to be used as the request body, or string for plain content
+ /// Optional: content type
+ ///
+ /// Thrown if request body type cannot be resolved
+ /// This method will try to figure out the right content type based on the request data format and the provided content type
+ public RestRequest AddBody(object obj, ContentType? contentType = null) {
+ if (contentType == null) {
+ return request.RequestFormat switch {
+ DataFormat.Json => request.AddJsonBody(obj, contentType),
+ DataFormat.Xml => request.AddXmlBody(obj, contentType),
+ DataFormat.Binary => request.AddParameter(new BodyParameter("", obj, ContentType.Binary)),
+ _ => request.AddParameter(new BodyParameter("", obj.ToString()!, ContentType.Plain))
+ };
+ }
+
+ return
+ obj is string str ? request.AddStringBody(str, contentType) :
+ obj is byte[] bytes ? request.AddParameter(new BodyParameter("", bytes, contentType, DataFormat.Binary)) :
+ contentType.Value.Contains("xml") ? request.AddXmlBody(obj, contentType) :
+ contentType.Value.Contains("json") ? request.AddJsonBody(obj, contentType) :
+ throw new ArgumentException("Non-string body found with unsupported content type", nameof(obj));
}
- return
- obj is string str ? request.AddStringBody(str, contentType) :
- obj is byte[] bytes ? request.AddParameter(new BodyParameter("", bytes, contentType, DataFormat.Binary)) :
- contentType.Value.Contains("xml") ? request.AddXmlBody(obj, contentType) :
- contentType.Value.Contains("json") ? request.AddJsonBody(obj, contentType) :
- throw new ArgumentException("Non-string body found with unsupported content type", nameof(obj));
- }
+ ///
+ /// Adds a string body and figures out the content type from the data format specified. You can, for example, add a JSON string
+ /// using this method as request body, using DataFormat.Json/>
+ ///
+ /// String body
+ /// for the content
+ ///
+ public RestRequest AddStringBody(string body, DataFormat dataFormat) {
+ var contentType = ContentType.FromDataFormat(dataFormat);
+ request.RequestFormat = dataFormat;
+ return request.AddParameter(new BodyParameter("", body, contentType));
+ }
- ///
- /// Adds a string body and figures out the content type from the data format specified. You can, for example, add a JSON string
- /// using this method as request body, using DataFormat.Json/>
- ///
- /// Request instance
- /// String body
- /// for the content
- ///
- public static RestRequest AddStringBody(this RestRequest request, string body, DataFormat dataFormat) {
- var contentType = ContentType.FromDataFormat(dataFormat);
- request.RequestFormat = dataFormat;
- return request.AddParameter(new BodyParameter("", body, contentType));
- }
+ ///
+ /// Adds a string body to the request using the specified content type.
+ ///
+ /// String body
+ /// Content type of the body
+ ///
+ public RestRequest AddStringBody(string body, ContentType contentType)
+ => request.AddParameter(new BodyParameter(body, Ensure.NotNull(contentType, nameof(contentType))));
- ///
- /// Adds a string body to the request using the specified content type.
- ///
- /// Request instance
- /// String body
- /// Content type of the body
- ///
- public static RestRequest AddStringBody(this RestRequest request, string body, ContentType contentType)
- => request.AddParameter(new BodyParameter(body, Ensure.NotNull(contentType, nameof(contentType))));
+ ///
+ /// Adds a JSON body parameter to the request from a string
+ ///
+ /// Force serialize the top-level string
+ /// Optional: content type. Default is ContentType.Json
+ /// JSON string to be used as a body
+ ///
+ public RestRequest AddJsonBody(string jsonString, bool forceSerialize, ContentType? contentType = null) {
+ request.RequestFormat = DataFormat.Json;
- ///
- /// Adds a JSON body parameter to the request from a string
- ///
- /// Request instance
- /// Force serialize the top-level string
- /// Optional: content type. Default is ContentType.Json
- /// JSON string to be used as a body
- ///
- public static RestRequest AddJsonBody(this RestRequest request, string jsonString, bool forceSerialize, ContentType? contentType = null) {
- request.RequestFormat = DataFormat.Json;
+ return !forceSerialize
+ ? request.AddStringBody(jsonString, DataFormat.Json)
+ : request.AddParameter(new JsonParameter(jsonString, contentType));
+ }
- return !forceSerialize
- ? request.AddStringBody(jsonString, DataFormat.Json)
- : request.AddParameter(new JsonParameter(jsonString, contentType));
- }
+ ///
+ /// Adds a JSON body parameter to the request
+ ///
+ /// Object that will be serialized to JSON
+ /// Optional: content type. Default is ContentType.Json
+ ///
+ public RestRequest AddJsonBody(T obj, ContentType? contentType = null) where T : class {
+ request.RequestFormat = DataFormat.Json;
- ///
- /// Adds a JSON body parameter to the request
- ///
- /// Request instance
- /// Object that will be serialized to JSON
- /// Optional: content type. Default is ContentType.Json
- ///
- public static RestRequest AddJsonBody(this RestRequest request, T obj, ContentType? contentType = null) where T : class {
- request.RequestFormat = DataFormat.Json;
+ return obj is string str
+ ? request.AddStringBody(str, DataFormat.Json)
+ : request.AddParameter(new JsonParameter(obj, contentType));
+ }
- return obj is string str
- ? request.AddStringBody(str, DataFormat.Json)
- : request.AddParameter(new JsonParameter(obj, contentType));
- }
+ ///
+ /// Adds an XML body parameter to the request
+ ///
+ /// Object that will be serialized to XML
+ /// Optional: content type. Default is ContentType.Xml
+ /// Optional: XML namespace
+ ///
+ public RestRequest AddXmlBody(T obj, ContentType? contentType = null, string xmlNamespace = "")
+ where T : class {
+ request.RequestFormat = DataFormat.Xml;
- ///
- /// Adds an XML body parameter to the request
- ///
- /// Request instance
- /// Object that will be serialized to XML
- /// Optional: content type. Default is ContentType.Xml
- /// Optional: XML namespace
- ///
- public static RestRequest AddXmlBody(this RestRequest request, T obj, ContentType? contentType = null, string xmlNamespace = "")
- where T : class {
- request.RequestFormat = DataFormat.Xml;
+ return obj is string str
+ ? request.AddStringBody(str, DataFormat.Xml)
+ : request.AddParameter(new XmlParameter(obj, xmlNamespace, contentType));
+ }
- return obj is string str
- ? request.AddStringBody(str, DataFormat.Xml)
- : request.AddParameter(new XmlParameter(obj, xmlNamespace, contentType));
+ RestRequest AddBodyParameter(string? name, object value)
+ => name != null && name.Contains('/')
+ ? request.AddBody(value, name)
+ : request.AddParameter(new BodyParameter(name, value, ContentType.Plain));
}
- static RestRequest AddBodyParameter(this RestRequest request, string? name, object value)
- => name != null && name.Contains('/')
- ? request.AddBody(value, name)
- : request.AddParameter(new BodyParameter(name, value, ContentType.Plain));
}
\ No newline at end of file
diff --git a/src/RestSharp/Request/RestRequestExtensions.File.cs b/src/RestSharp/Request/RestRequestExtensions.File.cs
index 816916adf..4674338ac 100644
--- a/src/RestSharp/Request/RestRequestExtensions.File.cs
+++ b/src/RestSharp/Request/RestRequestExtensions.File.cs
@@ -15,77 +15,74 @@
namespace RestSharp;
public static partial class RestRequestExtensions {
- ///
- /// Adds a file parameter to the request body. The file will be read from disk as a stream.
- ///
/// Request instance
- /// Parameter name
- /// Full path to the file
- /// Optional: content type
- /// File parameter header options
- ///
- public static RestRequest AddFile(
- this RestRequest request,
- string name,
- string path,
- ContentType? contentType = null,
- FileParameterOptions? options = null
- )
- => request.AddFile(FileParameter.FromFile(path, name, contentType, options));
+ extension(RestRequest request) {
+ ///
+ /// Adds a file parameter to the request body. The file will be read from disk as a stream.
+ ///
+ /// Parameter name
+ /// Full path to the file
+ /// Optional: content type
+ /// File parameter header options
+ ///
+ public RestRequest AddFile(
+ string name,
+ string path,
+ ContentType? contentType = null,
+ FileParameterOptions? options = null
+ )
+ => request.AddFile(FileParameter.FromFile(path, name, contentType, options));
- ///
- /// Adds bytes to the request as file attachment
- ///
- /// Request instance
- /// Parameter name
- /// File content as bytes
- /// File name
- /// Optional: content type. Default is "application/octet-stream"
- /// File parameter header options
- ///
- public static RestRequest AddFile(
- this RestRequest request,
- string name,
- byte[] bytes,
- string fileName,
- ContentType? contentType = null,
- FileParameterOptions? options = null
- )
- => request.AddFile(FileParameter.Create(name, bytes, fileName, contentType, options));
+ ///
+ /// Adds bytes to the request as file attachment
+ ///
+ /// Parameter name
+ /// File content as bytes
+ /// File name
+ /// Optional: content type. Default is "application/octet-stream"
+ /// File parameter header options
+ ///
+ public RestRequest AddFile(
+ string name,
+ byte[] bytes,
+ string fileName,
+ ContentType? contentType = null,
+ FileParameterOptions? options = null
+ )
+ => request.AddFile(FileParameter.Create(name, bytes, fileName, contentType, options));
- ///
- /// Adds a file attachment to the request, where the file content will be retrieved from a given stream
- ///
- /// Request instance
- /// Parameter name
- /// Function that returns a stream with the file content
- /// File name
- /// Optional: content type. Default is "application/octet-stream"
- /// File parameter header options
- ///
- public static RestRequest AddFile(
- this RestRequest request,
- string name,
- Func getFile,
- string fileName,
- ContentType? contentType = null,
- FileParameterOptions? options = null
- )
- => request.AddFile(FileParameter.Create(name, getFile, fileName, contentType, options));
+ ///
+ /// Adds a file attachment to the request, where the file content will be retrieved from a given stream
+ ///
+ /// Parameter name
+ /// Function that returns a stream with the file content
+ /// File name
+ /// Optional: content type. Default is "application/octet-stream"
+ /// File parameter header options
+ ///
+ public RestRequest AddFile(
+ string name,
+ Func getFile,
+ string fileName,
+ ContentType? contentType = null,
+ FileParameterOptions? options = null
+ )
+ => request.AddFile(FileParameter.Create(name, getFile, fileName, contentType, options));
- internal static void ValidateParameters(this RestRequest request) {
- if (!request.AlwaysSingleFileAsContent) return;
+ internal void ValidateParameters() {
+ if (!request.AlwaysSingleFileAsContent) return;
- var postParametersExists = request.Parameters.GetContentParameters(request.Method).Any();
- var bodyParametersExists = request.Parameters.Any(p => p.Type == ParameterType.RequestBody);
+ var postParametersExists = request.Parameters.GetContentParameters(request.Method).Any();
+ var bodyParametersExists = request.Parameters.Any(p => p.Type == ParameterType.RequestBody);
- if (request.AlwaysMultipartFormData)
- throw new ArgumentException("Failed to put file as content because flag AlwaysMultipartFormData is enabled");
+ if (request.AlwaysMultipartFormData)
+ throw new ArgumentException("Failed to put file as content because flag AlwaysMultipartFormData is enabled");
- if (postParametersExists)
- throw new ArgumentException("Failed to put file as content because POST parameters were added");
+ if (postParametersExists)
+ throw new ArgumentException("Failed to put file as content because POST parameters were added");
- if (bodyParametersExists)
- throw new ArgumentException("Failed to put file as content because body parameters were added");
+ if (bodyParametersExists)
+ throw new ArgumentException("Failed to put file as content because body parameters were added");
+ }
}
}
\ No newline at end of file
diff --git a/src/RestSharp/Request/RestRequestExtensions.Headers.cs b/src/RestSharp/Request/RestRequestExtensions.Headers.cs
index d3e6b7815..2838db65f 100644
--- a/src/RestSharp/Request/RestRequestExtensions.Headers.cs
+++ b/src/RestSharp/Request/RestRequestExtensions.Headers.cs
@@ -15,93 +15,89 @@
namespace RestSharp;
public static partial class RestRequestExtensions {
- ///
- /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource.
- ///
/// Request instance
- /// Header name
- /// Header values
- ///
- public static RestRequest AddHeader(this RestRequest request, string name, string[] values) {
- foreach (var value in values) {
- AddHeader(request, name, value);
+ extension(RestRequest request) {
+ ///
+ /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource.
+ ///
+ /// Header name
+ /// Header values
+ ///
+ public RestRequest AddHeader(string name, string[] values) {
+ foreach (var value in values) {
+ AddHeader(request, name, value);
+ }
+
+ return request;
}
- return request;
- }
+ ///
+ /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource.
+ ///
+ /// Header name
+ /// Header value
+ ///
+ public RestRequest AddHeader(string name, string value)
+ => request.AddParameter(new HeaderParameter(name, value));
- ///
- /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource.
- ///
- /// Request instance
- /// Header name
- /// Header value
- ///
- public static RestRequest AddHeader(this RestRequest request, string name, string value)
- => request.AddParameter(new HeaderParameter(name, value));
+ ///
+ /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource.
+ ///
+ /// Header name
+ /// Header value
+ ///
+ public RestRequest AddHeader(string name, T value) where T : struct
+ => request.AddHeader(name, Ensure.NotNull(value.ToString(), nameof(value)));
- ///
- /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource.
- ///
- /// Request instance
- /// Header name
- /// Header value
- ///
- public static RestRequest AddHeader(this RestRequest request, string name, T value) where T : struct
- => request.AddHeader(name, Ensure.NotNull(value.ToString(), nameof(value)));
+ ///
+ /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource.
+ /// The existing header with the same name will be replaced.
+ ///
+ /// Header name
+ /// Header value
+ ///
+ public RestRequest AddOrUpdateHeader(string name, string value)
+ => request.AddOrUpdateParameter(new HeaderParameter(name, value));
- ///
- /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource.
- /// The existing header with the same name will be replaced.
- ///
- /// Request instance
- /// Header name
- /// Header value
- ///
- public static RestRequest AddOrUpdateHeader(this RestRequest request, string name, string value)
- => request.AddOrUpdateParameter(new HeaderParameter(name, value));
+ ///
+ /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource.
+ /// The existing header with the same name will be replaced.
+ ///
+ /// Header name
+ /// Header value
+ ///
+ public RestRequest AddOrUpdateHeader(string name, T value) where T : struct
+ => request.AddOrUpdateHeader(name, Ensure.NotNull(value.ToString(), nameof(value)));
- ///
- /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource.
- /// The existing header with the same name will be replaced.
- ///
- /// Request instance
- /// Header name
- /// Header value
- ///
- public static RestRequest AddOrUpdateHeader(this RestRequest request, string name, T value) where T : struct
- => request.AddOrUpdateHeader(name, Ensure.NotNull(value.ToString(), nameof(value)));
+ ///
+ /// Adds multiple headers to the request, using the key-value pairs provided.
+ ///
+ /// Collection of key-value pairs, where key will be used as header name, and value as header value
+ ///
+ public RestRequest AddHeaders(ICollection> headers) {
+ CheckAndThrowsDuplicateKeys(headers);
- ///
- /// Adds multiple headers to the request, using the key-value pairs provided.
- ///
- /// Request instance
- /// Collection of key-value pairs, where key will be used as header name, and value as header value
- ///
- public static RestRequest AddHeaders(this RestRequest request, ICollection> headers) {
- CheckAndThrowsDuplicateKeys(headers);
+ foreach (var header in headers) {
+ request.AddHeader(header.Key, header.Value);
+ }
- foreach (var header in headers) {
- request.AddHeader(header.Key, header.Value);
+ return request;
}
- return request;
- }
+ ///
+ /// Adds or updates multiple headers to the request, using the key-value pairs provided. Existing headers with the same name will be replaced.
+ ///
+ /// Collection of key-value pairs, where key will be used as header name, and value as header value
+ ///
+ public RestRequest AddOrUpdateHeaders(ICollection> headers) {
+ CheckAndThrowsDuplicateKeys(headers);
- ///
- /// Adds or updates multiple headers to the request, using the key-value pairs provided. Existing headers with the same name will be replaced.
- ///
- /// Request instance
- /// Collection of key-value pairs, where key will be used as header name, and value as header value
- ///
- public static RestRequest AddOrUpdateHeaders(this RestRequest request, ICollection> headers) {
- CheckAndThrowsDuplicateKeys(headers);
+ foreach (var pair in headers) {
+ request.AddOrUpdateHeader(pair.Key, pair.Value);
+ }
- foreach (var pair in headers) {
- request.AddOrUpdateHeader(pair.Key, pair.Value);
+ return request;
}
-
- return request;
}
static void CheckAndThrowsDuplicateKeys(ICollection> headers) {
diff --git a/src/RestSharp/Request/RestRequestExtensions.Object.cs b/src/RestSharp/Request/RestRequestExtensions.Object.cs
index 173035790..fbfd2715f 100644
--- a/src/RestSharp/Request/RestRequestExtensions.Object.cs
+++ b/src/RestSharp/Request/RestRequestExtensions.Object.cs
@@ -15,51 +15,51 @@
namespace RestSharp;
public static partial class RestRequestExtensions {
- ///
- /// Gets object properties and adds each property as a form data parameter
- ///
/// Request instance
- /// Object to add as form data
- /// Properties to include, or nothing to include everything. The array will be sorted.
- ///
- public static RestRequest AddObject(this RestRequest request, T obj, params string[] includedProperties) where T : class {
- var props = obj.GetProperties(includedProperties);
+ extension(RestRequest request) {
+ ///
+ /// Gets object properties and adds each property as a form data parameter
+ ///
+ /// Object to add as form data
+ /// Properties to include, or nothing to include everything. The array will be sorted.
+ ///
+ public RestRequest AddObject(T obj, params string[] includedProperties) where T : class {
+ var props = obj.GetProperties(includedProperties);
- foreach (var prop in props) {
- request.AddParameter(prop.Name, prop.Value, prop.Encode);
- }
+ foreach (var prop in props) {
+ request.AddParameter(prop.Name, prop.Value, prop.Encode);
+ }
- return request;
- }
+ return request;
+ }
- ///
- /// Gets object properties and adds each property as a form data parameter
- ///
- ///
- /// This method gets public instance properties from the provided type
- /// rather than from itself, which allows for caching of properties and
- /// other optimizations. If you don't know the type at runtime, or wish to use properties not
- /// available from the provided type parameter, consider using
- ///
- /// Request instance
- /// Object to add as form data
- /// Properties to include, or nothing to include everything. The array will be sorted.
- ///
- public static RestRequest AddObjectStatic(this RestRequest request, T obj, params string[] includedProperties) where T : class
- => request.AddParameters(PropertyCache.GetParameters(obj, includedProperties));
+ ///
+ /// Gets object properties and adds each property as a form data parameter
+ ///
+ ///
+ /// This method gets public instance properties from the provided type
+ /// rather than from itself, which allows for caching of properties and
+ /// other optimizations. If you don't know the type at runtime, or wish to use properties not
+ /// available from the provided type parameter, consider using
+ ///
+ /// Object to add as form data
+ /// Properties to include, or nothing to include everything. The array will be sorted.
+ ///
+ public RestRequest AddObjectStatic(T obj, params string[] includedProperties) where T : class
+ => request.AddParameters(PropertyCache.GetParameters(obj, includedProperties));
- ///
- /// Gets object properties and adds each property as a form data parameter
- ///
- ///
- /// This method gets public instance properties from the provided type
- /// rather than from itself, which allows for caching of properties and
- /// other optimizations. If you don't know the type at runtime, or wish to use properties not
- /// available from the provided type parameter, consider using
- ///
- /// Request instance
- /// Object to add as form data
- ///
- public static RestRequest AddObjectStatic(this RestRequest request, T obj) where T : class
- => request.AddParameters(PropertyCache.GetParameters(obj));
+ ///
+ /// Gets object properties and adds each property as a form data parameter
+ ///
+ ///
+ /// This method gets public instance properties from the provided type
+ /// rather than from itself, which allows for caching of properties and
+ /// other optimizations. If you don't know the type at runtime, or wish to use properties not
+ /// available from the provided type parameter, consider using
+ ///
+ /// Object to add as form data
+ ///
+ public RestRequest AddObjectStatic(T obj) where T : class
+ => request.AddParameters(PropertyCache.GetParameters(obj));
+ }
}
\ No newline at end of file
diff --git a/src/RestSharp/Request/RestRequestExtensions.Query.cs b/src/RestSharp/Request/RestRequestExtensions.Query.cs
index 96ffae191..265dc360d 100644
--- a/src/RestSharp/Request/RestRequestExtensions.Query.cs
+++ b/src/RestSharp/Request/RestRequestExtensions.Query.cs
@@ -15,27 +15,28 @@
namespace RestSharp;
public static partial class RestRequestExtensions {
- ///
- /// Adds a query string parameter to the request. The request resource should not contain any placeholders for this parameter.
- /// The parameter will be added to the request URL as a query string using name=value format.
- ///
/// Request instance
- /// Parameter name
- /// Parameter value
- /// Encode the value or not, default true
- ///
- public static RestRequest AddQueryParameter(this RestRequest request, string name, string? value, bool encode = true)
- => request.AddParameter(new QueryParameter(name, value, encode));
+ extension(RestRequest request) {
+ ///
+ /// Adds a query string parameter to the request. The request resource should not contain any placeholders for this parameter.
+ /// The parameter will be added to the request URL as a query string using name=value format.
+ ///
+ /// Parameter name
+ /// Parameter value
+ /// Encode the value or not, default true
+ ///
+ public RestRequest AddQueryParameter(string name, string? value, bool encode = true)
+ => request.AddParameter(new QueryParameter(name, value, encode));
- ///
- /// Adds a query string parameter to the request. The request resource should not contain any placeholders for this parameter.
- /// The parameter will be added to the request URL as a query string using name=value format.
- ///
- /// Request instance
- /// Parameter name
- /// Parameter value
- /// Encode the value or not, default true
- ///
- public static RestRequest AddQueryParameter(this RestRequest request, string name, T value, bool encode = true) where T : struct
- => request.AddQueryParameter(name, value.ToString(), encode);
+ ///
+ /// Adds a query string parameter to the request. The request resource should not contain any placeholders for this parameter.
+ /// The parameter will be added to the request URL as a query string using name=value format.
+ ///
+ /// Parameter name
+ /// Parameter value
+ /// Encode the value or not, default true
+ ///
+ public RestRequest AddQueryParameter(string name, T value, bool encode = true) where T : struct
+ => request.AddQueryParameter(name, value.ToString(), encode);
+ }
}
\ No newline at end of file
diff --git a/src/RestSharp/Request/RestRequestExtensions.Url.cs b/src/RestSharp/Request/RestRequestExtensions.Url.cs
index 9470b7af9..ff7d4e829 100644
--- a/src/RestSharp/Request/RestRequestExtensions.Url.cs
+++ b/src/RestSharp/Request/RestRequestExtensions.Url.cs
@@ -15,27 +15,28 @@
namespace RestSharp;
public static partial class RestRequestExtensions {
- ///
- /// Adds a URL segment parameter to the request. The resource URL must have a placeholder for the parameter for it to work.
- /// For example, if you add a URL segment parameter with the name "id", the resource URL should contain {id} in its path.
- ///
/// Request instance
- /// Name of the parameter; must be matching a placeholder in the resource URL as {name}
- /// Value of the parameter
- /// Encode the value or not, default true
- ///
- public static RestRequest AddUrlSegment(this RestRequest request, string name, string? value, bool encode = true)
- => request.AddParameter(new UrlSegmentParameter(name, value, encode));
+ extension(RestRequest request) {
+ ///
+ /// Adds a URL segment parameter to the request. The resource URL must have a placeholder for the parameter for it to work.
+ /// For example, if you add a URL segment parameter with the name "id", the resource URL should contain {id} in its path.
+ ///
+ /// Name of the parameter; must be matching a placeholder in the resource URL as {name}
+ /// Value of the parameter
+ /// Encode the value or not, default true
+ ///
+ public RestRequest AddUrlSegment(string name, string? value, bool encode = true)
+ => request.AddParameter(new UrlSegmentParameter(name, value, encode));
- ///
- /// Adds a URL segment parameter to the request. The resource URL must have a placeholder for the parameter for it to work.
- /// For example, if you add a URL segment parameter with the name "id", the resource URL should contain {id} in its path.
- ///
- /// Request instance
- /// Name of the parameter; must be matching a placeholder in the resource URL as {name}
- /// Value of the parameter
- /// Encode the value or not, default true
- ///
- public static RestRequest AddUrlSegment(this RestRequest request, string name, T value, bool encode = true) where T : struct
- => request.AddUrlSegment(name, value.ToString(), encode);
+ ///
+ /// Adds a URL segment parameter to the request. The resource URL must have a placeholder for the parameter for it to work.
+ /// For example, if you add a URL segment parameter with the name "id", the resource URL should contain {id} in its path.
+ ///
+ /// Name of the parameter; must be matching a placeholder in the resource URL as {name}
+ /// Value of the parameter
+ /// Encode the value or not, default true
+ ///
+ public RestRequest AddUrlSegment(string name, T value, bool encode = true) where T : struct
+ => request.AddUrlSegment(name, value.ToString(), encode);
+ }
}
\ No newline at end of file
diff --git a/src/RestSharp/Request/RestRequestExtensions.cs b/src/RestSharp/Request/RestRequestExtensions.cs
index 57d2572a8..82323d07b 100644
--- a/src/RestSharp/Request/RestRequestExtensions.cs
+++ b/src/RestSharp/Request/RestRequestExtensions.cs
@@ -16,132 +16,126 @@ namespace RestSharp;
[PublicAPI]
public static partial class RestRequestExtensions {
- ///
- /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
- ///
///
- /// Name of the parameter
- /// Value of the parameter
- /// Encode the value or not, default true
- /// This request
- public static RestRequest AddParameter(this RestRequest request, string name, string? value, bool encode = true)
- => request.AddParameter(new GetOrPostParameter(name, value, encode));
+ extension(RestRequest request) {
+ ///
+ /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
+ ///
+ /// Name of the parameter
+ /// Value of the parameter
+ /// Encode the value or not, default true
+ /// This request
+ public RestRequest AddParameter(string name, string? value, bool encode = true)
+ => request.AddParameter(new GetOrPostParameter(name, value, encode));
- ///
- /// Adds a parameter of a given type to the request. It will create a typed parameter instance based on the type argument.
- /// It is not recommended to use this overload unless you must, as it doesn't provide any restrictions, and if the name-value-type
- /// combination doesn't match, it will throw.
- ///
- /// Request instance
- /// Name of the parameter, must be matching a placeholder in the resource URL as {name}
- /// Value of the parameter
- /// Enum value specifying what kind of parameter is being added
- /// Encode the value or not, default true
- ///
- public static RestRequest AddParameter(this RestRequest request, string? name, object value, ParameterType type, bool encode = true)
- => type == ParameterType.RequestBody
- ? request.AddBodyParameter(name, value)
- : request.AddParameter(Parameter.CreateParameter(name, value, type, encode));
+ ///
+ /// Adds a parameter of a given type to the request. It will create a typed parameter instance based on the type argument.
+ /// It is not recommended to use this overload unless you must, as it doesn't provide any restrictions, and if the name-value-type
+ /// combination doesn't match, it will throw.
+ ///
+ /// Name of the parameter, must be matching a placeholder in the resource URL as {name}
+ /// Value of the parameter
+ /// Enum value specifying what kind of parameter is being added
+ /// Encode the value or not, default true
+ ///
+ public RestRequest AddParameter(string? name, object value, ParameterType type, bool encode = true)
+ => type == ParameterType.RequestBody
+ ? request.AddBodyParameter(name, value)
+ : request.AddParameter(Parameter.CreateParameter(name, value, type, encode));
- ///
- /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT).
- /// The value will be converted to string.
- ///
- /// Request instance
- /// Name of the parameter
- /// Value of the parameter
- /// Encode the value or not, default true
- /// This request
- public static RestRequest AddParameter(this RestRequest request, string name, T value, bool encode = true) where T : struct
- => request.AddParameter(name, value.ToString(), encode);
+ ///
+ /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT).
+ /// The value will be converted to string.
+ ///
+ /// Name of the parameter
+ /// Value of the parameter
+ /// Encode the value or not, default true
+ /// This request
+ public RestRequest AddParameter(string name, T value, bool encode = true) where T : struct
+ => request.AddParameter(name, value.ToString(), encode);
- ///
- /// Adds or updates a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
- ///
- /// Request instance
- /// Name of the parameter
- /// Value of the parameter
- /// Encode the value or not, default true
- /// This request
- public static RestRequest AddOrUpdateParameter(this RestRequest request, string name, string? value, bool encode = true)
- => request.AddOrUpdateParameter(new GetOrPostParameter(name, value, encode));
+ ///
+ /// Adds or updates a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
+ ///
+ /// Name of the parameter
+ /// Value of the parameter
+ /// Encode the value or not, default true
+ /// This request
+ public RestRequest AddOrUpdateParameter(string name, string? value, bool encode = true)
+ => request.AddOrUpdateParameter(new GetOrPostParameter(name, value, encode));
- ///
- /// Adds or updates a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
- ///
- /// Request instance
- /// Name of the parameter
- /// Value of the parameter
- /// Encode the value or not, default true
- /// This request
- public static RestRequest AddOrUpdateParameter(this RestRequest request, string name, T value, bool encode = true) where T : struct
- => request.AddOrUpdateParameter(name, value.ToString(), encode);
+ ///
+ /// Adds or updates a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
+ ///
+ /// Name of the parameter
+ /// Value of the parameter
+ /// Encode the value or not, default true
+ /// This request
+ public RestRequest AddOrUpdateParameter(string name, T value, bool encode = true) where T : struct
+ => request.AddOrUpdateParameter(name, value.ToString(), encode);
- static RestRequest AddParameters(this RestRequest request, IEnumerable parameters) {
- request.Parameters.AddParameters(parameters);
- return request;
- }
+ RestRequest AddParameters(IEnumerable parameters) {
+ request.Parameters.AddParameters(parameters);
+ return request;
+ }
- ///
- /// Adds or updates request parameter of a given type. It will create a typed parameter instance based on the type argument.
- /// Parameter will be added or updated based on its name. If the request has a parameter with the same name, it will be updated.
- /// It is not recommended to use this overload unless you must, as it doesn't provide any restrictions, and if the name-value-type
- /// combination doesn't match, it will throw.
- ///
- /// Request instance
- /// Name of the parameter, must be matching a placeholder in the resource URL as {name}
- /// Value of the parameter
- /// Enum value specifying what kind of parameter is being added
- /// Encode the value or not, default true
- ///
- public static RestRequest AddOrUpdateParameter(this RestRequest request, string name, object value, ParameterType type, bool encode = true) {
- request.RemoveParameter(name, type);
+ ///
+ /// Adds or updates request parameter of a given type. It will create a typed parameter instance based on the type argument.
+ /// Parameter will be added or updated based on its name. If the request has a parameter with the same name, it will be updated.
+ /// It is not recommended to use this overload unless you must, as it doesn't provide any restrictions, and if the name-value-type
+ /// combination doesn't match, it will throw.
+ ///
+ /// Name of the parameter, must be matching a placeholder in the resource URL as {name}
+ /// Value of the parameter
+ /// Enum value specifying what kind of parameter is being added
+ /// Encode the value or not, default true
+ ///
+ public RestRequest AddOrUpdateParameter(string name, object value, ParameterType type, bool encode = true) {
+ request.RemoveParameter(name, type);
- return type == ParameterType.RequestBody
- ? request.AddBodyParameter(name, value)
- : request.AddOrUpdateParameter(Parameter.CreateParameter(name, value, type, encode));
- }
+ return type == ParameterType.RequestBody
+ ? request.AddBodyParameter(name, value)
+ : request.AddOrUpdateParameter(Parameter.CreateParameter(name, value, type, encode));
+ }
- ///
- /// Adds or updates request parameter, given the parameter instance, for example or .
- /// It will replace an existing parameter with the same name.
- ///
- /// Request instance
- /// Parameter instance
- ///
- public static RestRequest AddOrUpdateParameter(this RestRequest request, Parameter parameter)
- => request.RemoveParameter(parameter.Name, parameter.Type).AddParameter(parameter);
+ ///
+ /// Adds or updates request parameter, given the parameter instance, for example or .
+ /// It will replace an existing parameter with the same name.
+ ///
+ /// Parameter instance
+ ///
+ public RestRequest AddOrUpdateParameter(Parameter parameter)
+ => request.RemoveParameter(parameter.Name, parameter.Type).AddParameter(parameter);
- ///
- /// Adds or updates multiple request parameters, given the parameter instance, for example
- /// or . Parameters with the same name will be replaced.
- ///
- /// Request instance
- /// Collection of parameter instances
- ///
- public static RestRequest AddOrUpdateParameters(this RestRequest request, IEnumerable parameters) {
- foreach (var parameter in parameters) request.AddOrUpdateParameter(parameter);
+ ///
+ /// Adds or updates multiple request parameters, given the parameter instance, for example
+ /// or . Parameters with the same name will be replaced.
+ ///
+ /// Collection of parameter instances
+ ///
+ public RestRequest AddOrUpdateParameters(IEnumerable parameters) {
+ foreach (var parameter in parameters) request.AddOrUpdateParameter(parameter);
- return request;
- }
+ return request;
+ }
- static RestRequest RemoveParameter(this RestRequest request, string? name, ParameterType type) {
- var p = request.Parameters.FirstOrDefault(x => x.Name == name && x.Type == type);
- return p != null ? request.RemoveParameter(p) : request;
- }
+ RestRequest RemoveParameter(string? name, ParameterType type) {
+ var p = request.Parameters.FirstOrDefault(x => x.Name == name && x.Type == type);
+ return p != null ? request.RemoveParameter(p) : request;
+ }
- ///
- /// Adds cookie to the cookie container.
- ///
- /// RestRequest to add the cookies to
- /// Cookie name
- /// Cookie value
- /// Cookie path
- /// Cookie domain, must not be an empty string
- ///
- public static RestRequest AddCookie(this RestRequest request, string name, string value, string path, string domain) {
- request.CookieContainer ??= new CookieContainer();
- request.CookieContainer.Add(new Cookie(name, value, path, domain));
- return request;
+ ///
+ /// Adds cookie to the cookie container.
+ ///
+ /// Cookie name
+ /// Cookie value
+ /// Cookie path
+ /// Cookie domain, must not be an empty string
+ ///
+ public RestRequest AddCookie(string name, string value, string path, string domain) {
+ request.CookieContainer ??= new();
+ request.CookieContainer.Add(new Cookie(name, value, path, domain));
+ return request;
+ }
}
}
\ No newline at end of file
diff --git a/src/RestSharp/Request/UriExtensions.cs b/src/RestSharp/Request/UriExtensions.cs
index 84a0d4977..bc48800cd 100644
--- a/src/RestSharp/Request/UriExtensions.cs
+++ b/src/RestSharp/Request/UriExtensions.cs
@@ -29,9 +29,9 @@ public static Uri MergeBaseUrlAndResource(this Uri? baseUrl, string? resource) {
: throw new ArgumentException("Both BaseUrl and Resource are empty", nameof(resource));
}
- var usingBaseUri = baseUrl.AbsoluteUri[^1] == '/' || assembled.IsEmpty() ? baseUrl : new Uri(baseUrl.AbsoluteUri + "/");
+ var usingBaseUri = baseUrl.AbsoluteUri[^1] == '/' || assembled.IsEmpty() ? baseUrl : new(baseUrl.AbsoluteUri + "/");
- return assembled != null ? new Uri(usingBaseUri, assembled) : baseUrl;
+ return assembled != null ? new(usingBaseUri, assembled) : baseUrl;
}
public static Uri AddQueryString(this Uri uri, string? query) {
diff --git a/src/RestSharp/Response/ResponseThrowExtension.cs b/src/RestSharp/Response/ResponseThrowExtension.cs
index 7c4e99aa9..01d5167af 100644
--- a/src/RestSharp/Response/ResponseThrowExtension.cs
+++ b/src/RestSharp/Response/ResponseThrowExtension.cs
@@ -16,17 +16,17 @@
namespace RestSharp;
public static class ResponseThrowExtension {
- public static RestResponse ThrowIfError(this RestResponse response) {
- var exception = response.GetException();
- if (exception != null) throw exception;
-
- return response;
+ extension(RestResponse response) {
+ public RestResponse ThrowIfError() {
+ var exception = response.GetException();
+ return exception != null ? throw exception : response;
+ }
}
- public static RestResponse ThrowIfError(this RestResponse response) {
- var exception = response.GetException();
- if (exception != null) throw exception;
-
- return response;
+ extension(RestResponse response) {
+ public RestResponse ThrowIfError() {
+ var exception = response.GetException();
+ return exception != null ? throw exception : response;
+ }
}
}
diff --git a/src/RestSharp/Response/RestResponseExtensions.cs b/src/RestSharp/Response/RestResponseExtensions.cs
index 32735f571..ed9b32721 100644
--- a/src/RestSharp/Response/RestResponseExtensions.cs
+++ b/src/RestSharp/Response/RestResponseExtensions.cs
@@ -15,49 +15,48 @@
namespace RestSharp;
public static class RestResponseExtensions {
- ///
- /// Gets the value of the header with the specified name.
- ///
/// Response object
- /// Name of the header
- /// Header value or null if the header is not found in the response
- public static string? GetHeaderValue(this RestResponse response, string headerName)
- => response.Headers?.FirstOrDefault(x => NameIs(x.Name, headerName))?.Value.ToString();
+ extension(RestResponse response) {
+ ///
+ /// Gets the value of the header with the specified name.
+ ///
+ /// Name of the header
+ /// Header value or null if the header is not found in the response
+ public string? GetHeaderValue(string headerName)
+ => response.Headers?.FirstOrDefault(x => NameIs(x.Name, headerName))?.Value.ToString();
- ///
- /// Gets all the values of the header with the specified name.
- ///
- /// Response object
- /// Name of the header
- /// Array of header values or empty array if the header is not found in the response
- public static string[] GetHeaderValues(this RestResponse response, string headerName)
- => response.Headers
- ?.Where(x => NameIs(x.Name, headerName))
- .Select(x => x.Value.ToString() ?? "")
- .ToArray() ??
- [];
+ ///
+ /// Gets all the values of the header with the specified name.
+ ///
+ /// Name of the header
+ /// Array of header values or empty array if the header is not found in the response
+ public string[] GetHeaderValues(string headerName)
+ => response.Headers
+ ?.Where(x => NameIs(x.Name, headerName))
+ .Select(x => x.Value.ToString() ?? "")
+ .ToArray() ??
+ [];
- ///
- /// Gets the value of the content header with the specified name.
- ///
- /// Response object
- /// Name of the header
- /// Header value or null if the content header is not found in the response
- public static string? GetContentHeaderValue(this RestResponse response, string headerName)
- => response.ContentHeaders?.FirstOrDefault(x => NameIs(x.Name, headerName))?.Value.ToString();
+ ///
+ /// Gets the value of the content header with the specified name.
+ ///
+ /// Name of the header
+ /// Header value or null if the content header is not found in the response
+ public string? GetContentHeaderValue(string headerName)
+ => response.ContentHeaders?.FirstOrDefault(x => NameIs(x.Name, headerName))?.Value.ToString();
- ///
- /// Gets all the values of the content header with the specified name.
- ///
- /// Response object
- /// Name of the header
- /// Array of header values or empty array if the content header is not found in the response
- public static string[] GetContentHeaderValues(this RestResponse response, string headerName)
- => response.ContentHeaders
- ?.Where(x => NameIs(x.Name, headerName))
- .Select(x => x.Value.ToString() ?? "")
- .ToArray() ??
- [];
+ ///
+ /// Gets all the values of the content header with the specified name.
+ ///
+ /// Name of the header
+ /// Array of header values or empty array if the content header is not found in the response
+ public string[] GetContentHeaderValues(string headerName)
+ => response.ContentHeaders
+ ?.Where(x => NameIs(x.Name, headerName))
+ .Select(x => x.Value.ToString() ?? "")
+ .ToArray() ??
+ [];
+ }
static bool NameIs(string? name, string headerName)
=> name != null && name.Equals(headerName, StringComparison.InvariantCultureIgnoreCase);
diff --git a/src/RestSharp/RestClient.Async.cs b/src/RestSharp/RestClient.Async.cs
index 3bbb3f210..8d064720c 100644
--- a/src/RestSharp/RestClient.Async.cs
+++ b/src/RestSharp/RestClient.Async.cs
@@ -125,7 +125,7 @@ async Task ExecuteRequestAsync(RestRequest request, CancellationTo
HttpResponseMessage? responseMessage;
// Make sure we have a cookie container if not provided in the request
- var cookieContainer = request.CookieContainer ??= new CookieContainer();
+ var cookieContainer = request.CookieContainer ??= new();
var headers = new RequestHeaders()
.AddHeaders(request.Parameters)
@@ -152,14 +152,14 @@ async Task ExecuteRequestAsync(RestRequest request, CancellationTo
}
}
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) {
@@ -215,11 +215,11 @@ internal static HttpMethod AsHttpMethod(Method method)
#if NET
Method.Patch => HttpMethod.Patch,
#else
- Method.Patch => new HttpMethod("PATCH"),
+ Method.Patch => new("PATCH"),
#endif
- Method.Merge => new HttpMethod("MERGE"),
- Method.Copy => new HttpMethod("COPY"),
- Method.Search => new HttpMethod("SEARCH"),
+ Method.Merge => new("MERGE"),
+ Method.Copy => new("COPY"),
+ Method.Search => new("SEARCH"),
_ => throw new ArgumentOutOfRangeException(nameof(method))
};
}
\ No newline at end of file
diff --git a/src/RestSharp/RestClient.Extensions.Delete.cs b/src/RestSharp/RestClient.Extensions.Delete.cs
index 839543519..c92636545 100644
--- a/src/RestSharp/RestClient.Extensions.Delete.cs
+++ b/src/RestSharp/RestClient.Extensions.Delete.cs
@@ -16,179 +16,164 @@
namespace RestSharp;
public static partial class RestClientExtensions {
- ///
- /// Executes a DELETE-style request asynchronously, authenticating if needed
- ///
///
- /// Request to be executed
- /// Cancellation token
- public static Task ExecuteDeleteAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default)
- => client.ExecuteAsync(request, Method.Delete, cancellationToken);
-
- ///
- /// Executes a DELETE-style request asynchronously, authenticating if needed
- ///
- ///
- /// Request resource
- /// Cancellation token
- public static Task ExecuteDeleteAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default)
- => client.ExecuteAsync(new(resource), Method.Delete, cancellationToken);
-
- ///
- /// Executes a DELETE-style synchronously, authenticating if needed
- ///
- ///
- /// Request resource
- public static RestResponse ExecuteDelete(this IRestClient client, string resource)
- => AsyncHelpers.RunSync(() => client.ExecuteDeleteAsync(resource));
-
- ///
- /// Executes a DELETE-style synchronously, authenticating if needed
- ///
- ///
- /// Request to be executed
- public static RestResponse ExecuteDelete(this IRestClient client, RestRequest request)
- => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Delete));
-
- ///
- /// Executes a DELETE-style request asynchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request to be executed
- /// The cancellation token
- /// Deserialized response content
- public static Task> ExecuteDeleteAsync(
- this IRestClient client,
- RestRequest request,
- CancellationToken cancellationToken = default
- )
- => client.ExecuteAsync(request, Method.Delete, cancellationToken);
-
- ///
- /// Executes a DELETE-style request asynchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request resource
- /// The cancellation token
- /// Deserialized response content
- public static Task> ExecuteDeleteAsync(
- this IRestClient client,
- string resource,
- CancellationToken cancellationToken = default
- )
- => client.ExecuteAsync(new(resource), Method.Delete, cancellationToken);
-
- ///
- /// Executes a DELETE-style request synchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request to be executed
- /// Deserialized response content
- public static RestResponse ExecuteDelete(this IRestClient client, RestRequest request)
- => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Delete));
-
- ///
- /// Executes a DELETE-style request synchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request resource
- /// Deserialized response content
- public static RestResponse ExecuteDelete(this IRestClient client, string resource)
- => AsyncHelpers.RunSync(() => client.ExecuteDeleteAsync(resource));
-
- ///
- /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// The request
- /// Cancellation token
- /// Expected result type
- ///
- public static async Task DeleteAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteAsync(request, Method.Delete, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError().Data;
+ extension(IRestClient client) {
+ ///
+ /// Executes a DELETE-style request asynchronously, authenticating if needed
+ ///
+ /// Request to be executed
+ /// Cancellation token
+ public Task ExecuteDeleteAsync(RestRequest request, CancellationToken cancellationToken = default)
+ => client.ExecuteAsync(request, Method.Delete, cancellationToken);
+
+ ///
+ /// Executes a DELETE-style request asynchronously, authenticating if needed
+ ///
+ /// Request resource
+ /// Cancellation token
+ public Task ExecuteDeleteAsync(string resource, CancellationToken cancellationToken = default)
+ => client.ExecuteAsync(new(resource), Method.Delete, cancellationToken);
+
+ ///
+ /// Executes a DELETE-style synchronously, authenticating if needed
+ ///
+ /// Request resource
+ public RestResponse ExecuteDelete(string resource)
+ => AsyncHelpers.RunSync(() => client.ExecuteDeleteAsync(resource));
+
+ ///
+ /// Executes a DELETE-style synchronously, authenticating if needed
+ ///
+ /// Request to be executed
+ public RestResponse ExecuteDelete(RestRequest request)
+ => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Delete));
+
+ ///
+ /// Executes a DELETE-style request asynchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request to be executed
+ /// The cancellation token
+ /// Deserialized response content
+ public Task> ExecuteDeleteAsync(
+ RestRequest request,
+ CancellationToken cancellationToken = default
+ )
+ => client.ExecuteAsync(request, Method.Delete, cancellationToken);
+
+ ///
+ /// Executes a DELETE-style request asynchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request resource
+ /// The cancellation token
+ /// Deserialized response content
+ public Task> ExecuteDeleteAsync(
+ string resource,
+ CancellationToken cancellationToken = default
+ )
+ => client.ExecuteAsync(new(resource), Method.Delete, cancellationToken);
+
+ ///
+ /// Executes a DELETE-style request synchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request to be executed
+ /// Deserialized response content
+ public RestResponse ExecuteDelete(RestRequest request)
+ => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Delete));
+
+ ///
+ /// Executes a DELETE-style request synchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request resource
+ /// Deserialized response content
+ public RestResponse ExecuteDelete(string resource)
+ => AsyncHelpers.RunSync(() => client.ExecuteDeleteAsync(resource));
+
+ ///
+ /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// The request
+ /// Cancellation token
+ /// Expected result type
+ ///
+ public async Task DeleteAsync(RestRequest request, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteAsync(request, Method.Delete, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError().Data;
+ }
+
+ ///
+ /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// Request resource
+ /// Cancellation token
+ /// Expected result type
+ ///
+ public async Task DeleteAsync(string resource, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteAsync(new(resource), Method.Delete, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError().Data;
+ }
+
+ ///
+ /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// The request
+ /// Expected result type
+ ///
+ public T? Delete(RestRequest request) => AsyncHelpers.RunSync(() => client.DeleteAsync(request));
+
+ ///
+ /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// Request resource
+ /// Expected result type
+ ///
+ public T? Delete(string resource) => AsyncHelpers.RunSync(() => client.DeleteAsync(resource));
+
+ ///
+ /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// Request resource
+ /// Cancellation token
+ ///
+ public async Task DeleteAsync(string resource, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteAsync(new(resource), Method.Delete, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError();
+ }
+
+ ///
+ /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// Request resource
+ ///
+ public RestResponse Delete(string resource) => AsyncHelpers.RunSync(() => client.DeleteAsync(resource));
+
+ ///
+ /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// The request
+ /// Cancellation token
+ ///
+ public async Task DeleteAsync(RestRequest request, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteAsync(request, Method.Delete, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError();
+ }
+
+ ///
+ /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// The request
+ ///
+ public RestResponse Delete(RestRequest request) => AsyncHelpers.RunSync(() => client.DeleteAsync(request));
}
-
- ///
- /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// Request resource
- /// Cancellation token
- /// Expected result type
- ///
- public static async Task DeleteAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteAsync(new(resource), Method.Delete, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError().Data;
- }
-
- ///
- /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// The request
- /// Expected result type
- ///
- public static T? Delete(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.DeleteAsync(request));
-
- ///
- /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// Request resource
- /// Expected result type
- ///
- public static T? Delete(this IRestClient client, string resource) => AsyncHelpers.RunSync(() => client.DeleteAsync(resource));
-
- ///
- /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// Request resource
- /// Cancellation token
- ///
- public static async Task DeleteAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteAsync(new(resource), Method.Delete, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError();
- }
-
- ///
- /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// Request resource
- ///
- public static RestResponse Delete(this IRestClient client, string resource) => AsyncHelpers.RunSync(() => client.DeleteAsync(resource));
-
- ///
- /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// The request
- /// Cancellation token
- ///
- public static async Task DeleteAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteAsync(request, Method.Delete, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError();
- }
-
- ///
- /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// The request
- ///
- public static RestResponse Delete(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.DeleteAsync(request));
}
\ No newline at end of file
diff --git a/src/RestSharp/RestClient.Extensions.Get.cs b/src/RestSharp/RestClient.Extensions.Get.cs
index 1a4306844..1dae80183 100644
--- a/src/RestSharp/RestClient.Extensions.Get.cs
+++ b/src/RestSharp/RestClient.Extensions.Get.cs
@@ -16,212 +16,195 @@
namespace RestSharp;
public static partial class RestClientExtensions {
- ///
- /// Executes a GET-style asynchronously, authenticating if needed.
- ///
///
- /// Request to be executed
- /// Cancellation token
- public static Task ExecuteGetAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default)
- => client.ExecuteAsync(request, Method.Get, cancellationToken);
-
- ///
- /// Executes a GET-style asynchronously, authenticating if needed.
- ///
- ///
- /// Request resource
- /// Cancellation token
- public static Task ExecuteGetAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default)
- => client.ExecuteAsync(new RestRequest(resource), Method.Get, cancellationToken);
-
- ///
- /// Executes a GET-style synchronously, authenticating if needed
- ///
- ///
- /// Request to be executed
- public static RestResponse ExecuteGet(this IRestClient client, RestRequest request)
- => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Get));
-
- ///
- /// Executes a GET-style request asynchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request to be executed
- /// Cancellation token
- /// Deserialized response content
- public static Task> ExecuteGetAsync(
- this IRestClient client,
- RestRequest request,
- CancellationToken cancellationToken = default
- )
- => client.ExecuteAsync(request, Method.Get, cancellationToken);
-
- ///
- /// Executes a GET-style request to the specified resource URL asynchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request resource
- /// Cancellation token
- /// Deserialized response content
- public static Task> ExecuteGetAsync(
- this IRestClient client,
- string resource,
- CancellationToken cancellationToken = default
- )
- => client.ExecuteAsync(new RestRequest(resource), Method.Get, cancellationToken);
-
- ///
- /// Executes a GET-style request synchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request to be executed
- /// Deserialized response content
- public static RestResponse ExecuteGet(this IRestClient client, RestRequest request)
- => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Get));
-
- ///
- /// Executes a GET-style request synchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request resource
- /// Deserialized response content
- public static RestResponse ExecuteGet(this IRestClient client, string resource)
- => AsyncHelpers.RunSync(() => client.ExecuteGetAsync(resource));
-
- ///
- /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// The request
- /// Cancellation token
- ///
- public static async Task GetAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteGetAsync(request, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError();
- }
+ extension(IRestClient client) {
+ ///
+ /// Executes a GET-style asynchronously, authenticating if needed.
+ ///
+ /// Request to be executed
+ /// Cancellation token
+ public Task ExecuteGetAsync(RestRequest request, CancellationToken cancellationToken = default)
+ => client.ExecuteAsync(request, Method.Get, cancellationToken);
+
+ ///
+ /// Executes a GET-style asynchronously, authenticating if needed.
+ ///
+ /// Request resource
+ /// Cancellation token
+ public Task ExecuteGetAsync(string resource, CancellationToken cancellationToken = default)
+ => client.ExecuteAsync(new(resource), Method.Get, cancellationToken);
+
+ ///
+ /// Executes a GET-style synchronously, authenticating if needed
+ ///
+ /// Request to be executed
+ public RestResponse ExecuteGet(RestRequest request)
+ => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Get));
+
+ ///
+ /// Executes a GET-style request asynchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request to be executed
+ /// Cancellation token
+ /// Deserialized response content
+ public Task> ExecuteGetAsync(
+ RestRequest request,
+ CancellationToken cancellationToken = default
+ )
+ => client.ExecuteAsync(request, Method.Get, cancellationToken);
+
+ ///
+ /// Executes a GET-style request to the specified resource URL asynchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request resource
+ /// Cancellation token
+ /// Deserialized response content
+ public Task> ExecuteGetAsync(
+ string resource,
+ CancellationToken cancellationToken = default
+ )
+ => client.ExecuteAsync(new(resource), Method.Get, cancellationToken);
+
+ ///
+ /// Executes a GET-style request synchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request to be executed
+ /// Deserialized response content
+ public RestResponse ExecuteGet(RestRequest request)
+ => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Get));
+
+ ///
+ /// Executes a GET-style request synchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request resource
+ /// Deserialized response content
+ public RestResponse ExecuteGet(string resource)
+ => AsyncHelpers.RunSync(() => client.ExecuteGetAsync(resource));
+
+ ///
+ /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// The request
+ /// Cancellation token
+ ///
+ public async Task GetAsync(RestRequest request, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteGetAsync(request, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError();
+ }
- ///
- /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// The request
- ///
- public static RestResponse Get(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.GetAsync(request));
-
- ///
- /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// The request
- /// Cancellation token
- /// Expected result type
- ///
- public static async Task GetAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteGetAsync(request, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError().Data;
- }
+ ///
+ /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// The request
+ ///
+ public RestResponse Get(RestRequest request) => AsyncHelpers.RunSync(() => client.GetAsync(request));
+
+ ///
+ /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// The request
+ /// Cancellation token
+ /// Expected result type
+ ///
+ public async Task GetAsync(RestRequest request, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteGetAsync(request, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError().Data;
+ }
- ///
- /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// The request
- /// Expected result type
- ///
- public static T? Get(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.GetAsync(request));
-
- ///
- /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response.
- ///
- /// RestClient instance
- /// Resource URL
- /// Cancellation token
- /// Response object type
- ///
- public static Task GetAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default)
- => client.GetAsync(new RestRequest(resource), cancellationToken);
-
- [Obsolete("Use GetAsync instead")]
- public static Task GetJsonAsync(
- this IRestClient client,
- string resource,
- CancellationToken cancellationToken = default
- )
- => client.GetAsync(resource, cancellationToken);
-
- [Obsolete("Use Get instead")]
- public static TResponse? GetJson(this IRestClient client, string resource)
- => AsyncHelpers.RunSync(() => client.GetAsync(resource));
-
- ///
- /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response.
- ///
- /// RestClient instance
- /// Resource URL
- /// Response object type
- /// Deserialized response object
- public static TResponse? Get(this IRestClient client, string resource)
- => AsyncHelpers.RunSync(() => client.GetAsync(resource));
-
- ///
- /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response.
- ///
- /// RestClient instance
- /// Resource URL
- /// Parameters to pass to the request
- /// Cancellation token
- /// Response object type
- /// Deserialized response object
- public static Task GetAsync(
- this IRestClient client,
- string resource,
- object parameters,
- CancellationToken cancellationToken = default
- ) {
- var props = parameters.GetProperties();
- var request = new RestRequest(resource);
-
- foreach (var prop in props) {
- Parameter parameter = resource.Contains($"{prop.Name}")
- ? new UrlSegmentParameter(prop.Name, prop.Value!, prop.Encode)
- : new QueryParameter(prop.Name, prop.Value, prop.Encode);
- request.AddParameter(parameter);
+ ///
+ /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// The request
+ /// Expected result type
+ ///
+ public T? Get(RestRequest request) => AsyncHelpers.RunSync(() => client.GetAsync(request));
+
+ ///
+ /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response.
+ ///
+ /// Resource URL
+ /// Cancellation token
+ /// Response object type
+ ///
+ public Task GetAsync(string resource, CancellationToken cancellationToken = default)
+ => client.GetAsync(new RestRequest(resource), cancellationToken);
+
+ [Obsolete("Use GetAsync instead")]
+ public Task GetJsonAsync(
+ string resource,
+ CancellationToken cancellationToken = default
+ )
+ => client.GetAsync(resource, cancellationToken);
+
+ [Obsolete("Use Get instead")]
+ public TResponse? GetJson(string resource)
+ => AsyncHelpers.RunSync(() => client.GetAsync(resource));
+
+ ///
+ /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response.
+ ///
+ /// Resource URL
+ /// Response object type
+ /// Deserialized response object
+ public TResponse? Get(string resource)
+ => AsyncHelpers.RunSync(() => client.GetAsync(resource));
+
+ ///
+ /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response.
+ ///
+ /// Resource URL
+ /// Parameters to pass to the request
+ /// Cancellation token
+ /// Response object type
+ /// Deserialized response object
+ public Task GetAsync(
+ string resource,
+ object parameters,
+ CancellationToken cancellationToken = default
+ ) {
+ var props = parameters.GetProperties();
+ var request = new RestRequest(resource);
+
+ foreach (var prop in props) {
+ Parameter parameter = resource.Contains($"{prop.Name}")
+ ? new UrlSegmentParameter(prop.Name, prop.Value!, prop.Encode)
+ : new QueryParameter(prop.Name, prop.Value, prop.Encode);
+ request.AddParameter(parameter);
+ }
+
+ return client.GetAsync(request, cancellationToken);
}
- return client.GetAsync(request, cancellationToken);
+ [Obsolete("Use GetAsync instead")]
+ public Task GetJsonAsync(
+ string resource,
+ object parameters,
+ CancellationToken cancellationToken = default
+ )
+ => client.GetAsync(resource, parameters, cancellationToken);
+
+ ///
+ /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response.
+ ///
+ /// Resource URL
+ /// Parameters to pass to the request
+ /// Response object type
+ /// Deserialized response object
+ public TResponse? Get(string resource, object parameters)
+ => AsyncHelpers.RunSync(() => client.GetAsync(resource, parameters));
+
+ [Obsolete("Use Get instead")]
+ public TResponse? GetJson(string resource, object parameters)
+ => client.Get(resource, parameters);
}
-
- [Obsolete("Use GetAsync instead")]
- public static Task GetJsonAsync(
- this IRestClient client,
- string resource,
- object parameters,
- CancellationToken cancellationToken = default
- )
- => client.GetAsync(resource, parameters, cancellationToken);
-
- ///
- /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response.
- ///
- /// RestClient instance
- /// Resource URL
- /// Parameters to pass to the request
- /// Response object type
- /// Deserialized response object
- public static TResponse? Get(this IRestClient client, string resource, object parameters)
- => AsyncHelpers.RunSync(() => client.GetAsync(resource, parameters));
-
- [Obsolete("Use Get instead")]
- public static TResponse? GetJson(this IRestClient client, string resource, object parameters)
- => client.Get(resource, parameters);
}
\ No newline at end of file
diff --git a/src/RestSharp/RestClient.Extensions.Head.cs b/src/RestSharp/RestClient.Extensions.Head.cs
index c30402c02..ee4a9421a 100644
--- a/src/RestSharp/RestClient.Extensions.Head.cs
+++ b/src/RestSharp/RestClient.Extensions.Head.cs
@@ -16,91 +16,85 @@
namespace RestSharp;
public static partial class RestClientExtensions {
- ///
- /// Executes a HEAD-style request asynchronously, authenticating if needed
- ///
///
- /// Request to be executed
- /// Cancellation token
- public static Task ExecuteHeadAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default)
- => client.ExecuteAsync(request, Method.Head, cancellationToken);
+ extension(IRestClient client) {
+ ///
+ /// Executes a HEAD-style request asynchronously, authenticating if needed
+ ///
+ /// Request to be executed
+ /// Cancellation token
+ public Task ExecuteHeadAsync(RestRequest request, CancellationToken cancellationToken = default)
+ => client.ExecuteAsync(request, Method.Head, cancellationToken);
- ///
- /// Executes a HEAD-style synchronously, authenticating if needed
- ///
- ///
- /// Request to be executed
- public static RestResponse ExecuteHead(this IRestClient client, RestRequest request)
- => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Head));
+ ///
+ /// Executes a HEAD-style synchronously, authenticating if needed
+ ///
+ /// Request to be executed
+ public RestResponse ExecuteHead(RestRequest request)
+ => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Head));
- ///
- /// Executes a HEAD-style request asynchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request to be executed
- /// The cancellation token
- /// Deserialized response content
- public static Task> ExecuteHeadAsync(
- this IRestClient client,
- RestRequest request,
- CancellationToken cancellationToken = default
- )
- => client.ExecuteAsync(request, Method.Head, cancellationToken);
+ ///
+ /// Executes a HEAD-style request asynchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request to be executed
+ /// The cancellation token
+ /// Deserialized response content
+ public Task> ExecuteHeadAsync(
+ RestRequest request,
+ CancellationToken cancellationToken = default
+ )
+ => client.ExecuteAsync(request, Method.Head, cancellationToken);
- ///
- /// Executes a HEAD-style request synchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request to be executed
- /// Deserialized response content
- public static RestResponse ExecuteHead(this IRestClient client, RestRequest request)
- => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Head));
+ ///
+ /// Executes a HEAD-style request synchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request to be executed
+ /// Deserialized response content
+ public RestResponse ExecuteHead(RestRequest request)
+ => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Head));
- ///
- /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// The request
- /// Cancellation token
- /// Expected result type
- ///
- public static async Task HeadAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteAsync(request, Method.Head, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError().Data;
- }
+ ///
+ /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// The request
+ /// Cancellation token
+ /// Expected result type
+ ///
+ public async Task HeadAsync(RestRequest request, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteAsync(request, Method.Head, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError().Data;
+ }
- ///
- /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// The request
- /// Expected result type
- ///
- public static T? Head(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.HeadAsync(request));
+ ///
+ /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// The request
+ /// Expected result type
+ ///
+ public T? Head(RestRequest request) => AsyncHelpers.RunSync(() => client.HeadAsync(request));
- ///
- /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// The request
- /// Cancellation token
- ///
- public static async Task HeadAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteAsync(request, Method.Head, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError();
- }
+ ///
+ /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// The request
+ /// Cancellation token
+ ///
+ public async Task HeadAsync(RestRequest request, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteAsync(request, Method.Head, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError();
+ }
- ///
- /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// The request
- ///
- public static RestResponse Head(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.HeadAsync(request));
+ ///
+ /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// The request
+ ///
+ public RestResponse Head(RestRequest request) => AsyncHelpers.RunSync(() => client.HeadAsync(request));
+ }
}
diff --git a/src/RestSharp/RestClient.Extensions.Options.cs b/src/RestSharp/RestClient.Extensions.Options.cs
index dccb907d9..82882394a 100644
--- a/src/RestSharp/RestClient.Extensions.Options.cs
+++ b/src/RestSharp/RestClient.Extensions.Options.cs
@@ -16,91 +16,85 @@
namespace RestSharp;
public static partial class RestClientExtensions {
- ///
- /// Executes an OPTIONS-style request asynchronously, authenticating if needed
- ///
///
- /// Request to be executed
- /// Cancellation token
- public static Task ExecuteOptionsAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default)
- => client.ExecuteAsync(request, Method.Options, cancellationToken);
+ extension(IRestClient client) {
+ ///
+ /// Executes an OPTIONS-style request asynchronously, authenticating if needed
+ ///
+ /// Request to be executed
+ /// Cancellation token
+ public Task ExecuteOptionsAsync(RestRequest request, CancellationToken cancellationToken = default)
+ => client.ExecuteAsync(request, Method.Options, cancellationToken);
- ///
- /// Executes a OPTIONS-style synchronously, authenticating if needed
- ///
- ///
- /// Request to be executed
- public static RestResponse ExecuteOptions(this IRestClient client, RestRequest request)
- => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Options));
+ ///
+ /// Executes a OPTIONS-style synchronously, authenticating if needed
+ ///
+ /// Request to be executed
+ public RestResponse ExecuteOptions(RestRequest request)
+ => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Options));
- ///
- /// Executes a OPTIONS-style request asynchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request to be executed
- /// The cancellation token
- /// Deserialized response content
- public static Task> ExecuteOptionsAsync(
- this IRestClient client,
- RestRequest request,
- CancellationToken cancellationToken = default
- )
- => client.ExecuteAsync(request, Method.Options, cancellationToken);
+ ///
+ /// Executes a OPTIONS-style request asynchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request to be executed
+ /// The cancellation token
+ /// Deserialized response content
+ public Task> ExecuteOptionsAsync(
+ RestRequest request,
+ CancellationToken cancellationToken = default
+ )
+ => client.ExecuteAsync(request, Method.Options, cancellationToken);
- ///
- /// Executes a OPTIONS-style request synchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
- ///
- /// Request to be executed
- /// Deserialized response content
- public static RestResponse ExecuteOptions(this IRestClient client, RestRequest request)
- => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Options));
+ ///
+ /// Executes a OPTIONS-style request synchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request to be executed
+ /// Deserialized response content
+ public RestResponse ExecuteOptions(RestRequest request)
+ => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Options));
- ///
- /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// The request
- /// Cancellation token
- ///
- public static async Task OptionsAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteAsync(request, Method.Options, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError();
- }
+ ///
+ /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// The request
+ /// Cancellation token
+ ///
+ public async Task OptionsAsync(RestRequest request, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteAsync(request, Method.Options, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError();
+ }
- ///
- /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed.
- ///
- /// RestClient instance
- /// The request
- ///
- public static RestResponse Options(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.OptionsAsync(request));
+ ///
+ /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed.
+ ///
+ /// The request
+ ///
+ public RestResponse Options(RestRequest request) => AsyncHelpers.RunSync(() => client.OptionsAsync(request));
- ///
- /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// The request
- /// Cancellation token
- /// Expected result type
- ///
- public static async Task OptionsAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) {
- var response = await client.ExecuteAsync(request, Method.Options, cancellationToken).ConfigureAwait(false);
- return response.ThrowIfError().Data;
- }
+ ///
+ /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// The request
+ /// Cancellation token
+ /// Expected result type
+ ///
+ public async Task OptionsAsync(RestRequest request, CancellationToken cancellationToken = default) {
+ var response = await client.ExecuteAsync(request, Method.Options, cancellationToken).ConfigureAwait(false);
+ return response.ThrowIfError().Data;
+ }
- ///
- /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed.
- /// The response data is deserialized to the Data property of the returned response object.
- ///
- /// RestClient instance
- /// The request
- /// Expected result type
- ///
- public static T? Options(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.OptionsAsync(request));
+ ///
+ /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed.
+ /// The response data is deserialized to the Data property of the returned response object.
+ ///
+ /// The request
+ /// Expected result type
+ ///
+ public T? Options(RestRequest request) => AsyncHelpers.RunSync(() => client.OptionsAsync(request));
+ }
}
diff --git a/src/RestSharp/RestClient.Extensions.Params.cs b/src/RestSharp/RestClient.Extensions.Params.cs
index a919fa8b4..cd3bb635c 100644
--- a/src/RestSharp/RestClient.Extensions.Params.cs
+++ b/src/RestSharp/RestClient.Extensions.Params.cs
@@ -16,83 +16,79 @@
namespace RestSharp;
public static partial class RestClientExtensions {
- ///
- /// Add a parameter to use on every request made with this client instance
- ///
/// instance
- /// to add
- ///
- public static IRestClient AddDefaultParameter(this IRestClient client, Parameter parameter) {
- client.DefaultParameters.AddParameter(parameter);
- return client;
- }
+ extension(IRestClient client) {
+ ///
+ /// Add a parameter to use on every request made with this client instance
+ ///
+ /// to add
+ ///
+ public IRestClient AddDefaultParameter(Parameter parameter) {
+ client.DefaultParameters.AddParameter(parameter);
+ return client;
+ }
- ///
- /// Adds a default HTTP parameter (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
- /// Used on every request made by this client instance
- ///
- /// instance
- /// Name of the parameter
- /// Value of the parameter
- /// This request
- public static IRestClient AddDefaultParameter(this IRestClient client, string name, string value)
- => client.AddDefaultParameter(new GetOrPostParameter(name, value));
+ ///
+ /// Adds a default HTTP parameter (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT)
+ /// Used on every request made by this client instance
+ ///
+ /// Name of the parameter
+ /// Value of the parameter
+ /// This request
+ public IRestClient AddDefaultParameter(string name, string value)
+ => client.AddDefaultParameter(new GetOrPostParameter(name, value));
- ///
- /// Adds a default parameter to the client options. There are four types of parameters:
- /// - GetOrPost: Either a QueryString value or encoded form value based on method
- /// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
- /// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
- /// - RequestBody: Used by AddBody() (not recommended to use directly)
- /// Used on every request made by this client instance
- ///
- /// instance
- /// Name of the parameter
- /// Value of the parameter
- /// The type of parameter to add
- /// This request
- public static IRestClient AddDefaultParameter(this IRestClient client, string name, object value, ParameterType type)
- => client.AddDefaultParameter(Parameter.CreateParameter(name, value, type));
+ ///
+ /// Adds a default parameter to the client options. There are four types of parameters:
+ /// - GetOrPost: Either a QueryString value or encoded form value based on method
+ /// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection
+ /// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId}
+ /// - RequestBody: Used by AddBody() (not recommended to use directly)
+ /// Used on every request made by this client instance
+ ///
+ /// Name of the parameter
+ /// Value of the parameter
+ /// The type of parameter to add
+ /// This request
+ public IRestClient AddDefaultParameter(string name, object value, ParameterType type)
+ => client.AddDefaultParameter(Parameter.CreateParameter(name, value, type));
- ///
- /// Adds a default header to the RestClient. Used on every request made by this client instance.
- ///
- /// instance
- /// Name of the header to add
- /// Value of the header to add
- ///
- public static IRestClient AddDefaultHeader(this IRestClient client, string name, string value)
- => client.AddDefaultParameter(new HeaderParameter(name, value));
+ ///
+ /// Adds a default header to the RestClient. Used on every request made by this client instance.
+ ///
+ /// Name of the header to add
+ /// Value of the header to add
+ ///
+ public IRestClient AddDefaultHeader(string name, string value)
+ => client.AddDefaultParameter(new HeaderParameter(name, value));
- ///
- /// Adds default headers to the RestClient. Used on every request made by this client instance.
- ///
- /// instance
- /// Dictionary containing the Names and Values of the headers to add
- ///
- public static IRestClient AddDefaultHeaders(this IRestClient client, Dictionary headers) {
- foreach (var header in headers) client.AddDefaultParameter(new HeaderParameter(header.Key, header.Value));
+ ///
+ /// Adds default headers to the RestClient. Used on every request made by this client instance.
+ ///
+ /// Dictionary containing the Names and Values of the headers to add
+ ///
+ public IRestClient AddDefaultHeaders(Dictionary headers) {
+ foreach (var header in headers) client.AddDefaultParameter(new HeaderParameter(header.Key, header.Value));
- return client;
- }
+ return client;
+ }
- ///
- /// Adds a default URL segment parameter to the RestClient. Used on every request made by this client instance.
- ///
- /// instance
- /// Name of the segment to add
- /// Value of the segment to add
- ///
- public static IRestClient AddDefaultUrlSegment(this IRestClient client, string name, string value)
- => client.AddDefaultParameter(new UrlSegmentParameter(name, value));
+ ///
+ /// Adds a default URL segment parameter to the RestClient. Used on every request made by this client instance.
+ ///
+ /// Name of the segment to add
+ /// Value of the segment to add
+ ///
+ public IRestClient AddDefaultUrlSegment(string name, string value)
+ => client.AddDefaultParameter(new UrlSegmentParameter(name, value));
- ///
- /// Adds a default URL query parameter to the RestClient. Used on every request made by this client instance.
- ///
- /// instance
- /// Name of the query parameter to add
- /// Value of the query parameter to add
- ///
- public static IRestClient AddDefaultQueryParameter(this IRestClient client, string name, string value)
- => client.AddDefaultParameter(new QueryParameter(name, value));
+ ///
+ /// Adds a default URL query parameter to the RestClient. Used on every request made by this client instance.
+ ///
+ /// Name of the query parameter to add
+ /// Value of the query parameter to add
+ ///
+ public IRestClient AddDefaultQueryParameter(string name, string value)
+ => client.AddDefaultParameter(new QueryParameter(name, value));
+ }
}
diff --git a/src/RestSharp/RestClient.Extensions.Patch.cs b/src/RestSharp/RestClient.Extensions.Patch.cs
index 44547ab7f..129f5fc19 100644
--- a/src/RestSharp/RestClient.Extensions.Patch.cs
+++ b/src/RestSharp/RestClient.Extensions.Patch.cs
@@ -16,93 +16,85 @@
namespace RestSharp;
public static partial class RestClientExtensions {
- ///
- /// Executes a PUT-style request asynchronously, authenticating if needed.
- /// The response content then gets deserialized to T.
- ///
- /// Target deserialization type
///
- /// Request to be executed
- /// The cancellation token
- /// Deserialized response content
- public static Task> ExecutePatchAsync(
- this IRestClient client,
- RestRequest request,
- CancellationToken cancellationToken = default
- )
- => client.ExecuteAsync(request, Method.Patch, cancellationToken);
+ extension(IRestClient client) {
+ ///
+ /// Executes a PUT-style request asynchronously, authenticating if needed.
+ /// The response content then gets deserialized to T.
+ ///
+ /// Target deserialization type
+ /// Request to be executed
+ /// The cancellation token
+ /// Deserialized response content
+ public Task> ExecutePatchAsync(
+ RestRequest request,
+ CancellationToken cancellationToken = default
+ )
+ => client.ExecuteAsync(request, Method.Patch, cancellationToken);
- ///