Skip to content

Commit 86a54f6

Browse files
committed
Merge pull request #440 from robertmiles3/escapedatastring-limit-fixer
UrlEncode fix for input strings > 32766 limit
2 parents 4f90124 + 66d151f commit 86a54f6

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Globalization;
4+
using System.Linq;
5+
using System.Text;
6+
using RestSharp.Extensions;
7+
using Xunit;
8+
9+
namespace RestSharp.Tests
10+
{
11+
public class StringExtensionsTests
12+
{
13+
[Fact]
14+
public void UrlEncode_Throws_ArgumentNullException_For_Null_Input()
15+
{
16+
const string nullString = null;
17+
Assert.Throws<System.ArgumentNullException>(
18+
delegate
19+
{
20+
nullString.UrlEncode();
21+
});
22+
}
23+
24+
[Fact]
25+
public void UrlEncode_Returns_Correct_Length_When_Less_Than_Limit()
26+
{
27+
const int numLessThanLimit = 32766;
28+
string stringWithLimitLength = new string('*', numLessThanLimit);
29+
Assert.True(stringWithLimitLength.UrlEncode().Length == numLessThanLimit);
30+
}
31+
32+
[Fact]
33+
public void UrlEncode_Returns_Correct_Length_When_More_Than_Limit()
34+
{
35+
const int numGreaterThanLimit = 65000;
36+
string stringWithLimitLength = new string('*', numGreaterThanLimit);
37+
Assert.True(stringWithLimitLength.UrlEncode().Length == numGreaterThanLimit);
38+
}
39+
}
40+
}

RestSharp/Extensions/StringExtensions.cs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,24 @@ public static string UrlDecode(this string input)
4949
/// </summary>
5050
public static string UrlEncode(this string input)
5151
{
52-
return Uri.EscapeDataString(input);
52+
const int maxLength = 32766;
53+
if (input == null)
54+
throw new ArgumentNullException("input");
55+
56+
if (input.Length <= maxLength)
57+
return Uri.EscapeDataString(input);
58+
59+
StringBuilder sb = new StringBuilder(input.Length * 2);
60+
int index = 0;
61+
while (index < input.Length)
62+
{
63+
int length = Math.Min(input.Length - index, maxLength);
64+
string subString = input.Substring(index, length);
65+
sb.Append(Uri.EscapeDataString(subString));
66+
index += subString.Length;
67+
}
68+
69+
return sb.ToString();
5370
}
5471

5572
public static string HtmlDecode(this string input)

0 commit comments

Comments
 (0)