Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions Web.Test/Models/HttpBinPostResponse.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
using System.Text.Json.Serialization;
using Newtonsoft.Json;

namespace Web.Test.Models
{
public class HttpBinPostResponse : HttpBinResponseBase
{
[JsonPropertyName("data")]
public string Data { get; set; }
[JsonProperty("data")]
public string Data { get; set; } = string.Empty;

[JsonPropertyName("files")]
public Dictionary<string, string> Files { get; set; }
[JsonProperty("files")]
public Dictionary<string, string> Files { get; set; } = [];

[JsonPropertyName("form")]
public Dictionary<string, string> Form { get; set; }
[JsonProperty("form")]
public Dictionary<string, string> Form { get; set; } = [];

[JsonPropertyName("json")]
public object Json { get; set; }
[JsonProperty("json")]
public object Json { get; set; } = new();
}
}
44 changes: 22 additions & 22 deletions Web.Test/Models/HttpBinResponseBase.cs
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
using System.Text.Json.Serialization;
using Newtonsoft.Json;

namespace Web.Test.Models
{
public class HttpBinResponseBase
{
[JsonPropertyName("args")]
public Dictionary<string, string> Args { get; set; }
[JsonProperty("args")]
public Dictionary<string, string> Args { get; set; } = [];

[JsonPropertyName("headers")]
public HttpBinResponseHeaders Headers { get; set; }
[JsonProperty("headers")]
public HttpBinResponseHeaders Headers { get; set; } = new();

[JsonPropertyName("origin")]
public string Origin { get; set; }
[JsonProperty("origin")]
public string Origin { get; set; } = string.Empty;

[JsonPropertyName("url")]
public string Url { get; set; }
[JsonProperty("url")]
public string Url { get; set; } = string.Empty;
}

public class HttpBinResponseHeaders
{
[JsonPropertyName("Accept")]
public string Accept { get; set; }
[JsonProperty("Accept")]
public string Accept { get; set; } = string.Empty;

[JsonPropertyName("Accept-Encoding")]
public string AcceptEncoding { get; set; }
[JsonProperty("Accept-Encoding")]
public string AcceptEncoding { get; set; } = string.Empty;

[JsonPropertyName("Accept-Language")]
public string AcceptLanguage { get; set; }
[JsonProperty("Accept-Language")]
public string AcceptLanguage { get; set; } = string.Empty;

[JsonPropertyName("Host")]
public string Host { get; set; }
[JsonProperty("Host")]
public string Host { get; set; } = string.Empty;

[JsonPropertyName("User-Agent")]
public string UserAgent { get; set; }
[JsonProperty("User-Agent")]
public string UserAgent { get; set; } = string.Empty;

[JsonPropertyName("X-Amzn-Trace-Id")]
public string AmazonTraceId { get; set; }
}
[JsonProperty("X-Amzn-Trace-Id")]
public string AmazonTraceId { get; set; } = string.Empty;
}
}
6 changes: 3 additions & 3 deletions Web.Test/RequestTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,12 @@ public async Task SendPostRequestWithFile()
Request request = new(TestPostUrl, HttpMethod.Post);
request
.SetContentType("text/plain")
.AddDocumentBody(fileBytes, fileName);
.AddByteBody(fileBytes, fileName);

Result<HttpBinPostFileResponse> result = await request.RunDocument<HttpBinPostFileResponse>();

AssertResponse(result, TestPostUrl);
StringAssert.Contains(result.Value.Data, "Hello world", "File content should contain 'Hello World'");
StringAssert.Contains(result.Value?.Data, "Hello world", "File content should contain 'Hello World'");
}

[TestMethod]
Expand Down Expand Up @@ -135,5 +135,5 @@ private void AssertImageResponse(Result<byte[]> result, string imgType)
Assert.IsTrue(result.Value.Length > 0, "Image data should not be empty");
File.WriteAllBytes($"test_image.{imgType}", result.Value);
}
}
}
}
51 changes: 41 additions & 10 deletions Web/API/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
public class Request
{
#region Variables

/// <summary>
/// The HTTP client used to send requests.
/// </summary>
Expand Down Expand Up @@ -51,22 +52,23 @@
/// <summary>
/// Gets the JSON body content of the request.
/// </summary>
public object Body { get; private set; } = null;

Check warning on line 55 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

Check warning on line 55 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

/// <summary>
/// Gets the binary document content of the request.
/// </summary>
public byte[] DocumentBody { get; private set; } = null;

Check warning on line 60 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

Check warning on line 60 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

/// <summary>
/// Gets the name of the binary document file.
/// </summary>
public string DocumentFileName { get; private set; } = null;
public string? DocumentFileName { get; private set; } = null;

/// <summary>
/// Gets the content type of the request.
/// </summary>
public string ContentType { get; private set; } = null;

Check warning on line 70 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

Check warning on line 70 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

#endregion

#region Constructors
Expand Down Expand Up @@ -202,12 +204,12 @@
}

/// <summary>
/// Adds a binary document to the request content.
/// Adds a <see cref="byte[]"/> to the request content.
/// </summary>
/// <param name="document">The binary file content.</param>
/// <param name="fileName">The name of the file.</param>
/// <returns>Instance</returns>
public Request AddDocumentBody(byte[] document, string fileName)
public Request AddByteBody(byte[] document, string? fileName)
{
DocumentBody = document;
DocumentFileName = fileName;
Expand Down Expand Up @@ -325,9 +327,38 @@
return result;
}

/// <summary>
/// Executes the HTTP request by sending the raw binary content directly in the request body,
/// without using multipart encoding. This method is ideal for APIs expecting direct binary content,
/// equivalent to Postman's "Binary" body type.
/// </summary>
/// <typeparam name="T">The type of the expected response.</typeparam>
/// <returns>
/// A <see cref="Result{T}"/> object containing the deserialized response, the HTTP status code,
/// and any error message if the request fails.
/// </returns>
public async Task<Result<T>> RunBinaryRaw<T>()
{
HttpRequestMessage request = BuildBaseRequest();

if (DocumentBody == null)
{
return new Result<T>
{
Error = "Document cannot be null",
StatusCode = 500
};
}

request.Content = new ByteArrayContent(DocumentBody);
request.Content.Headers.ContentType = new MediaTypeHeaderValue(ContentType ?? "application/octet-stream");

return await Process<T>(request);
}

#endregion

#region Private function
#region Private methods

/// <summary>
/// Constructs the URL for the request, including any query parameters if present.
Expand Down Expand Up @@ -403,19 +434,19 @@

if (response.IsSuccessStatusCode)
{
string? MediaType = response.Content?.Headers?.ContentType?.MediaType.ToLower();
string ContentResponse = await response.Content?.ReadAsStringAsync();
string? mediaType = response.Content?.Headers?.ContentType?.MediaType.ToLower();

Check warning on line 437 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 437 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
string contentResponse = await response.Content?.ReadAsStringAsync();

Check warning on line 438 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 438 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

switch (true)
{
case bool b when (MediaType.Contains("xml")):
case bool b when (mediaType.Contains("xml")):

Check warning on line 442 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 442 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
XmlSerializer xmlSerializer = new(typeof(T));
StringReader reader = new(ContentResponse);
StringReader reader = new(contentResponse);

result.Value = (T)xmlSerializer.Deserialize(reader);

Check warning on line 446 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.

Check warning on line 446 in Web/API/Request.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.
break;
case bool b when (MediaType.Contains("application/json")):
result.Value = JsonConvert.DeserializeObject<T>(ContentResponse);
case bool b when (mediaType.Contains("application/json")):
result.Value = JsonConvert.DeserializeObject<T>(contentResponse);
break;
default:
result.Value = default;
Expand Down
6 changes: 3 additions & 3 deletions Web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Install-Package FrApp42.Net

```csharp
using FrApp42.Web.API;
using System.Text.Json.Serialization;
using Newtonsoft.Json;

string url = "your-url";

Expand All @@ -34,10 +34,10 @@ if (result.StatusCode == 200 && result.Value != null)

class MyModel
{
[JsonPropertyName("name")]
[JsonProperty("name")]
public string Name { get; set; }

[JsonPropertyName("description")]
[JsonProperty("description")]
public string Description { get; set; }
}
```
Expand Down
15 changes: 6 additions & 9 deletions Web/Web.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>FrApp42.$(MSBuildProjectName)</AssemblyName>
Expand All @@ -20,10 +20,14 @@
<PackageReadmeFile>README.md</PackageReadmeFile>
<Company>FrenchyApps42</Company>
<PackageIcon>logo.png</PackageIcon>
<Version>1.2.2</Version>
<Version>1.3.0</Version>
</PropertyGroup>

<ItemGroup>
<None Update="README.md">
<PackagePath>\</PackagePath>
<Pack>True</Pack>
</None>
<None Include="..\LICENCE.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
Expand All @@ -38,11 +42,4 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

<ItemGroup>
<None Update="README.md">
<PackagePath>\</PackagePath>
<Pack>True</Pack>
</None>
</ItemGroup>

</Project>
Loading