Skip to content

Commit

Permalink
Merge branch 'kendallb-feature/http-client-issue-1814' into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeyzimarev committed Jun 7, 2022
2 parents f3af0ce + 5339609 commit d3e1334
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 22 deletions.
25 changes: 18 additions & 7 deletions src/RestSharp/Request/RequestContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Net;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using RestSharp.Extensions;
using static RestSharp.KnownHeaders;

// ReSharper disable InvertIf
// ReSharper disable SuggestBaseTypeForParameter

Expand All @@ -26,8 +28,6 @@ class RequestContent : IDisposable {
readonly RestRequest _request;
readonly List<Stream> _streams = new();



HttpContent? Content { get; set; }

public RequestContent(RestClient client, RestRequest request) {
Expand Down Expand Up @@ -55,8 +55,7 @@ void AddFiles() {
_streams.Add(stream);
var fileContent = new StreamContent(stream);

if (file.ContentType != null)
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(file.ContentType);
if (file.ContentType != null) fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(file.ContentType);

fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {
Name = $"\"{file.Name}\"",
Expand Down Expand Up @@ -97,8 +96,7 @@ HttpContent GetSerialized() {

var content = serializer.Serialize(body);

if (content == null)
throw new SerializationException("Request body serialized to null");
if (content == null) throw new SerializationException("Request body serialized to null");

return new StringContent(
content,
Expand Down Expand Up @@ -150,20 +148,33 @@ void AddPostParameters(ParametersCollection? postParameters) {
// we got the multipart form already instantiated, just add parameters to it
foreach (var postParameter in postParameters!) {
var parameterName = postParameter.Name!;

mpContent.Add(
new StringContent(postParameter.Value!.ToString()!, _client.Options.Encoding, postParameter.ContentType),
_request.MultipartFormQuoteParameters ? $"\"{parameterName}\"" : parameterName
);
}
}
else {
// we should not have anything else except the parameters, so we send them as form URL encoded
#if NETCORE
// We should not have anything else except the parameters, so we send them as form URL encoded.
var formContent = new FormUrlEncodedContent(
_request.Parameters
.Where(x => x.Type == ParameterType.GetOrPost)
.Select(x => new KeyValuePair<string, string>(x.Name!, x.Value!.ToString()!))!
);
Content = formContent;
#else
// However due to bugs in HttpClient FormUrlEncodedContent (see https://github.com/restsharp/RestSharp/issues/1814) we
// do the encoding ourselves using WebUtility.UrlEncode instead.
var formData = _request.Parameters
.Where(x => x.Type == ParameterType.GetOrPost)
.Select(x => new KeyValuePair<string, string>(x.Name!, x.Value!.ToString()!))!;
var encodedItems = formData.Select(i => $"{WebUtility.UrlEncode(i.Key)}={WebUtility.UrlEncode(i.Value)}" /*.Replace("%20", "+")*/);
var encodedContent = new StringContent(string.Join("&", encodedItems), null, "application/x-www-form-urlencoded");

Content = encodedContent;
#endif
}
}

Expand Down
5 changes: 4 additions & 1 deletion test/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<IsTestProject>true</IsTestProject>
<IsPackable>false</IsPackable>
<TargetFramework>net6.0</TargetFramework>
<TargetFrameworks>net472;net6.0</TargetFrameworks>
<Nullable>disable</Nullable>
</PropertyGroup>

Expand All @@ -17,6 +17,9 @@
<PackageReference Include="AutoFixture" Version="4.17.0"/>
<PackageReference Include="FluentAssertions" Version="6.7.0"/>
</ItemGroup>
<ItemGroup Condition="$(TargetFramework) == 'net472'">
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net472" Version="1.0.2" PrivateAssets="All"/>
</ItemGroup>

<ItemGroup>
<Using Include="Xunit"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<IsTestProject>false</IsTestProject>
<TargetFrameworks>net6</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RestSharp\RestSharp.csproj" />
Expand Down
27 changes: 22 additions & 5 deletions test/RestSharp.Tests.Integrated/PostTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Net;
using RestSharp.Tests.Integrated.Server;

namespace RestSharp.Tests.Integrated;
Expand All @@ -14,23 +15,39 @@ public async Task Should_post_json() {
var request = new RestRequest("post/json").AddJsonBody(body);
var response = await _client.ExecutePostAsync<TestResponse>(request);

response.Data.Message.Should().Be(body.Data);
response!.Data!.Message.Should().Be(body.Data);
}

[Fact]
public async Task Should_post_json_with_PostAsync() {
var body = new TestRequest("foo", 100);
var request = new RestRequest("post/json").AddJsonBody(body);
var response = await _client.PostAsync<TestResponse>(request);

response.Message.Should().Be(body.Data);
response!.Message.Should().Be(body.Data);
}

[Fact]
public async Task Should_post_json_with_PostJsonAsync() {
var body = new TestRequest("foo", 100);
var response = await _client.PostJsonAsync<TestRequest, TestResponse>("post/json", body);

response.Message.Should().Be(body.Data);
response!.Message.Should().Be(body.Data);
}

[Fact]
public async Task Should_post_large_form_data() {
const int length = 1024 * 1024;

var superLongString = new string('?', length);
var request = new RestRequest("post/form", Method.Post).AddParameter("big_string", superLongString);
var response = await _client.ExecuteAsync<Response>(request);

response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Data!.Message.Should().Be($"Works! Length: {length}");
}

class Response {
public string Message { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Nullable>disable</Nullable>
<TargetFrameworks>net6</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RestSharp.Serializers.Xml\RestSharp.Serializers.Xml.csproj" />
Expand Down
1 change: 1 addition & 0 deletions test/RestSharp.Tests.Integrated/Server/TestServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public HttpServer(ITestOutputHelper output = null) {

// POST
_app.MapPost("/post/json", (TestRequest request) => new TestResponse { Message = request.Data });
_app.MapPost("/post/form", (HttpContext context) => new TestResponse { Message = $"Works! Length: {context.Request.Form["big_string"].ToString().Length}" });

IResult HandleHeaders(HttpContext ctx) {
var response = ctx.Request.Headers.Select(x => new TestServerResponse(x.Key, x.Value));
Expand Down
2 changes: 1 addition & 1 deletion test/RestSharp.Tests.Legacy/RestSharp.Tests.Legacy.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<TargetFramework>net472</TargetFramework>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<None Update="SampleData\boolean_from_string.xml" CopyToOutputDirectory="PreserveNewest" />
<None Update="SampleData\deserialize_as_list.xml" CopyToOutputDirectory="PreserveNewest" />
<None Update="SampleData\directlists.xml" CopyToOutputDirectory="PreserveNewest" />
<None Update="SampleData\eventful.xml" CopyToOutputDirectory="PreserveNewest" />
<None Update="SampleData\eventful.xml" CopyToOutputDirectory="Always" />
<None Update="SampleData\Goodreads.xml" CopyToOutputDirectory="PreserveNewest" />
<None Update="SampleData\GoodreadsFormatError.xml" CopyToOutputDirectory="PreserveNewest" />
<None Update="SampleData\GoogleWeather.xml" CopyToOutputDirectory="PreserveNewest" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,25 @@
using RestSharp.Serializers.Xml;
using RestSharp.Tests.Serializers.Xml.SampleClasses;

namespace RestSharp.Tests.Serializers.Xml;
namespace RestSharp.Tests.Serializers.Xml;

public class XmlAttributeDeserializerTests {
readonly ITestOutputHelper _output;

const string GuidString = "AC1FC4BC-087A-4242-B8EE-C53EBE9887A5";

#if NETCORE
readonly string _sampleDataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SampleData");
#else
readonly string _sampleDataPath = Path.Combine(Directory.GetCurrentDirectory(), "SampleData");
#endif

string PathFor(string sampleFile) => Path.Combine(_sampleDataPath, sampleFile);

public XmlAttributeDeserializerTests(ITestOutputHelper output) {
_output = output;
}

[Fact]
public void Can_Deserialize_Lists_of_Simple_Types() {
var xmlPath = PathFor("xmllists.xml");
Expand All @@ -24,7 +34,7 @@ public void Can_Deserialize_Lists_of_Simple_Types() {

Assert.NotEmpty(output.Numbers);
Assert.False(output.Names[0].Length == 0);
Assert.False(output.Numbers.Sum() == 0);
Assert.False(output.Numbers.Sum() == 0);
}

[Fact]
Expand Down Expand Up @@ -572,7 +582,7 @@ static string CreateUnderscoresXml() {
friends.Add(
new XElement(
"Friend",
new XElement("Name", "Friend" + i),
new XElement("Name", "Friend" + i),
new XAttribute("Since", DateTime.Now.Year - i)
)
);
Expand Down Expand Up @@ -621,7 +631,7 @@ static string CreateLowercaseUnderscoresXml() {
friends.Add(
new XElement(
"Friend",
new XElement("Name", "Friend" + i),
new XElement("Name", "Friend" + i),
new XAttribute("Since", DateTime.Now.Year - i)
)
);
Expand Down Expand Up @@ -670,7 +680,7 @@ static string CreateDashesXml() {
friends.Add(
new XElement(
"Friend",
new XElement("Name", "Friend" + i),
new XElement("Name", "Friend" + i),
new XAttribute("Since", DateTime.Now.Year - i)
)
);
Expand Down Expand Up @@ -738,7 +748,7 @@ static string CreateElementsXml() {
friends.Add(
new XElement(
"Friend",
new XElement("Name", "Friend" + i),
new XElement("Name", "Friend" + i),
new XElement("Since", DateTime.Now.Year - i)
)
);
Expand Down Expand Up @@ -870,4 +880,4 @@ static string CreateXmlWithAttributesAndNullValuesAndPopulatedValues() {

return doc.ToString();
}
}
}
4 changes: 4 additions & 0 deletions test/RestSharp.Tests.Serializers.Xml/XmlDeserializerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ namespace RestSharp.Tests.Serializers.Xml;
public class XmlDeserializerTests {
const string GuidString = "AC1FC4BC-087A-4242-B8EE-C53EBE9887A5";

#if NETCORE
readonly string _sampleDataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SampleData");
#else
readonly string _sampleDataPath = Path.Combine(Directory.GetCurrentDirectory(), "SampleData");
#endif

string PathFor(string sampleFile) => Path.Combine(_sampleDataPath, sampleFile);

Expand Down

0 comments on commit d3e1334

Please sign in to comment.