diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs
index 99b843b7..459b1a96 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs
@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
///
/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId} route.
///
-public class GetAlbumEndpoint : BaseEndpoint
+public class GetAlbumEndpoint : BaseEndpoint
{
private readonly IQueryHandler> _getAlbumQueryHandler;
@@ -45,7 +45,7 @@ public class GetAlbumEndpoint : BaseEndpoint
/// The request object.
/// Cancellation token that can be used to stop the execution.
- public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs
index 11ce25b1..4427ab78 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs
@@ -17,7 +17,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
///
/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks route.
///
-public class GetAlbumTracksEndpoint : BaseEndpoint
+public class GetAlbumTracksEndpoint : BaseEndpoint
{
private readonly IQueryHandler>> _getAlbumTracksQueryHandler;
@@ -46,7 +46,7 @@ public class GetAlbumTracksEndpoint : BaseEndpoint
/// The request object.
/// Cancellation token that can be used to stop the execution.
- public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs
index bf1efd34..be109ed4 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs
@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
///
/// API endpoint for the /libraries/{libraryId}/artists/{artistId} route.
///
-public class GetArtistEndpoint : BaseEndpoint
+public class GetArtistEndpoint : BaseEndpoint
{
private readonly IQueryHandler> _getArtistQueryHandler;
@@ -45,7 +45,7 @@ public class GetArtistEndpoint : BaseEndpoint
/// The request object.
/// Cancellation token that can be used to stop the execution.
- public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs
index 2df64426..a9cff1f4 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs
@@ -17,7 +17,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
///
/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums route.
///
-public class GetArtistAlbumsEndpoint : BaseEndpoint
+public class GetArtistAlbumsEndpoint : BaseEndpoint
{
private readonly IQueryHandler>> _getArtistAlbumsQueryHandler;
@@ -46,7 +46,7 @@ public class GetArtistAlbumsEndpoint : BaseEndpoint
/// The request object.
/// Cancellation token that can be used to stop the execution.
- public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs
index 41af112b..ff734ea5 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs
@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
///
/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId} route.
///
-public class GetTrackEndpoint : BaseEndpoint
+public class GetTrackEndpoint : BaseEndpoint
{
private readonly IQueryHandler> _getTrackQueryHandler;
@@ -45,7 +45,7 @@ public class GetTrackEndpoint : BaseEndpoint
/// The request object.
/// Cancellation token that can be used to stop the execution.
- public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs
index bb13b274..8560391b 100644
--- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs
+++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs
@@ -60,12 +60,10 @@ public class ApiHttpClient : IApiHttpClient
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the GET request.
+ /// Thrown when the API returns an unsuccessful response.
public async Task GetAsync(string endpoint, CancellationToken cancellationToken = default)
{
- using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
- AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
- if (authenticationHeader is not null)
- request.Headers.Authorization = authenticationHeader;
+ using HttpRequestMessage request = CreateRequest(HttpMethod.Get, endpoint);
return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
@@ -78,10 +76,7 @@ public class ApiHttpClient : IApiHttpClient
/// An object, which allows for asynchronous iteration over the deserialized items.
public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
- using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
- AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
- if (authenticationHeader is not null)
- request.Headers.Authorization = authenticationHeader;
+ using HttpRequestMessage request = CreateRequest(HttpMethod.Get, endpoint);
// Send the request and expect only headers initially - this prevents the client from buffering the entire response.
using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
@@ -100,25 +95,16 @@ public class ApiHttpClient : IApiHttpClient
///
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
- /// A model containing the deserialized blob.
+ /// A model containing the raw blob bytes and their content type.
+ /// Thrown when the API returns an unsuccessful response.
public async Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default)
{
- using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
- AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
- if (authenticationHeader is not null)
- request.Headers.Authorization = authenticationHeader;
+ using HttpRequestMessage request = CreateRequest(HttpMethod.Get, endpoint);
using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
- // Read the content as a string, for error messages.
string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
- ProblemDetailsDto? problemDetails = null;
- try
- {
- problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
- }
- catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ }
- throw new ApiException(problemDetails, response.StatusCode);
+ throw CreateApiException(content, response, request);
}
// If the response is successful, read it as a byte array.
byte[] responseContent = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
@@ -127,30 +113,29 @@ public class ApiHttpClient : IApiHttpClient
}
///
- /// Sends a DELETE request to the specified as an asynchronous operation.
+ /// Sends a DELETE request to the specified as an asynchronous operation, discarding the response content.
///
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
+ /// Thrown when the API returns an unsuccessful response.
public async Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default)
{
- using HttpRequestMessage request = new(HttpMethod.Delete, endpoint);
- AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
- if (authenticationHeader is not null)
- request.Headers.Authorization = authenticationHeader;
- // Send the HTTP request and read the response.
- HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
- if (!response.IsSuccessStatusCode)
- {
- ProblemDetailsDto? problemDetails = null;
- string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
- // Attempt to deserialize the response content to ProblemDetailsDto if the request fails.
- try
- {
- problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
- }
- catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ }
- throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath);
- }
+ using HttpRequestMessage request = CreateRequest(HttpMethod.Delete, endpoint);
+ await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Sends a PUT request to the specified as an asynchronous operation, discarding the response content.
+ ///
+ /// The expected type of the payload content.
+ /// The API endpoint where the request is being sent.
+ /// The data to be serialized and sent to the API.
+ /// Cancellation token that can be used to stop the execution.
+ /// Thrown when the API returns an unsuccessful response.
+ public async Task PutIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default)
+ {
+ using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Put, endpoint, data);
+ await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
///
@@ -159,35 +144,40 @@ public class ApiHttpClient : IApiHttpClient
/// The expected type of the response content.
/// The expected type of the payload content.
/// The API endpoint where the request is being sent.
- /// The data to be serialized and send to the API.
+ /// The data to be serialized and sent to the API.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the PUT request.
+ /// Thrown when the API returns an unsuccessful response.
public async Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default)
{
- using HttpRequestMessage request = new(HttpMethod.Put, endpoint);
- AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
- if (authenticationHeader is not null)
- request.Headers.Authorization = authenticationHeader;
- request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
+ using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Put, endpoint, data);
return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
///
- /// Sends a POST request to the specified as an asynchronous operation and returns the result.
+ /// Sends a PUT request with a multipart form containing a single file to the specified as an asynchronous operation, and returns the result.
///
/// The expected type of the response content.
- /// The expected type of the payload content.
/// The API endpoint where the request is being sent.
- /// The data to be serialized and sent to the API.
+ /// The stream of the file to upload, or to send a multipart form without any file.
+ /// The name of the file to upload, or when no file is sent.
+ /// The name of the form field carrying the file.
/// Cancellation token that can be used to stop the execution.
- /// The deserialized response containing the result of the POST request.
- public async Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default)
+ /// The deserialized response containing the result of the PUT request.
+ /// Thrown when the API returns an unsuccessful response.
+ public async Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default)
{
- using HttpRequestMessage request = new(HttpMethod.Post, endpoint);
- AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
- if (authenticationHeader is not null)
- request.Headers.Authorization = authenticationHeader;
- request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
+ using MultipartFormDataContent form = [];
+ if (fileStream is not null)
+ {
+ // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known.
+ StreamContent fileContent = new(fileStream);
+ fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
+ form.Add(fileContent, fieldName, fileName ?? string.Empty);
+ }
+
+ using HttpRequestMessage request = CreateRequest(HttpMethod.Put, endpoint);
+ request.Content = form;
return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
@@ -201,6 +191,7 @@ public class ApiHttpClient : IApiHttpClient
/// The name of the form field carrying the file.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the POST request.
+ /// Thrown when the API returns an unsuccessful response.
public async Task PostMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default)
{
// The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known.
@@ -209,50 +200,116 @@ public class ApiHttpClient : IApiHttpClient
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, fieldName, fileName);
- using HttpRequestMessage request = new(HttpMethod.Post, endpoint)
- {
- Content = form
- };
- AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
- if (authenticationHeader is not null)
- request.Headers.Authorization = authenticationHeader;
+ using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint);
+ request.Content = form;
return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
///
- /// Sends a PUT request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result.
+ /// Sends a POST request without a payload to the specified as an asynchronous operation, discarding the response content.
+ ///
+ /// The API endpoint where the request is being sent.
+ /// Cancellation token that can be used to stop the execution.
+ /// Thrown when the API returns an unsuccessful response.
+ public async Task PostIgnoringResponseAsync(string endpoint, CancellationToken cancellationToken = default)
+ {
+ using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint);
+ await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Sends a POST request without a payload to the specified as an asynchronous operation, and returns the result.
///
/// The expected type of the response content.
/// The API endpoint where the request is being sent.
- /// The stream of the file to upload, or to send a multipart form without any file.
- /// The name of the file to upload, or when no file is sent.
- /// The name of the form field carrying the file.
/// Cancellation token that can be used to stop the execution.
- /// The deserialized response containing the result of the PUT request.
- public async Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default)
+ /// The deserialized response containing the result of the POST request.
+ /// Thrown when the API returns an unsuccessful response.
+ public async Task PostAsync(string endpoint, CancellationToken cancellationToken = default)
{
- using MultipartFormDataContent form = [];
- if (fileStream is not null)
- {
- // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known.
- StreamContent fileContent = new(fileStream);
- fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
- form.Add(fileContent, fieldName, fileName ?? string.Empty);
- }
+ using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint);
+ return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
+ }
- using HttpRequestMessage request = new(HttpMethod.Put, endpoint)
- {
- Content = form
- };
+ ///
+ /// Sends a POST request to the specified as an asynchronous operation, discarding the response content.
+ ///
+ /// The expected type of the payload content.
+ /// The API endpoint where the request is being sent.
+ /// The data to be serialized and sent to the API.
+ /// Cancellation token that can be used to stop the execution.
+ /// Thrown when the API returns an unsuccessful response.
+ public async Task PostIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default)
+ {
+ using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Post, endpoint, data);
+ await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Sends a POST request to the specified as an asynchronous operation and returns the result.
+ ///
+ /// The expected type of the response content.
+ /// The expected type of the payload content.
+ /// The API endpoint where the request is being sent.
+ /// The data to be serialized and sent to the API.
+ /// Cancellation token that can be used to stop the execution.
+ /// The deserialized response containing the result of the POST request.
+ /// Thrown when the API returns an unsuccessful response.
+ public async Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default)
+ {
+ using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Post, endpoint, data);
+ return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Creates an HTTP request for the specified and .
+ ///
+ /// The HTTP method of the request.
+ /// The API endpoint where the request is being sent.
+ /// The created .
+ private HttpRequestMessage CreateRequest(HttpMethod method, string endpoint)
+ {
+ HttpRequestMessage request = new(method, endpoint);
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
- return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
+ return request;
+ }
+
+ ///
+ /// Creates an HTTP request for the specified and , with the serialized as its JSON payload.
+ ///
+ /// The expected type of the payload content.
+ /// The HTTP method of the request.
+ /// The API endpoint where the request is being sent.
+ /// The data to be serialized and sent to the API.
+ /// The created .
+ private HttpRequestMessage CreateRequestWithPayload(HttpMethod method, string endpoint, TModel data)
+ {
+ HttpRequestMessage request = CreateRequest(method, endpoint);
+ request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
+ return request;
+ }
+
+ ///
+ /// Sends an HTTP request and reads the response content.
+ /// If the request fails, it attempts to deserialize the response content into a and throws an .
+ ///
+ /// The to be sent.
+ /// Cancellation token that can be used to stop the execution.
+ /// The raw response content.
+ /// Thrown if the response is not successful, with the if available.
+ private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
+ string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
+ if (response.IsSuccessStatusCode)
+ return content;
+ throw CreateApiException(content, response, request);
}
///
/// Sends an HTTP request and deserializes the response into the specified type if the request is successful.
- /// If the request fails, it attempts to deserialize the response content into a and throws an .
///
/// The expected type of the response content.
/// The to be sent.
@@ -261,28 +318,30 @@ public class ApiHttpClient : IApiHttpClient
/// Thrown if the response is not successful, with the if available.
private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
- // Send the HTTP request and read the response.
- HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
- string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
- // If the response is successful, deserialize the content to TResponse and return it.
- if (response.IsSuccessStatusCode)
+ string content = await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
+ // Handle empty content case.
+ if (string.IsNullOrEmpty(content))
+ return default!;
+ return JsonSerializer.Deserialize(content, _jsonOptions)!;
+ }
+
+ ///
+ /// Creates the exception thrown when an API request fails.
+ ///
+ /// The raw response content.
+ /// The failed HTTP response.
+ /// The HTTP request that failed.
+ /// The created .
+ private ApiException CreateApiException(string content, HttpResponseMessage response, HttpRequestMessage request)
+ {
+ ProblemDetailsDto? problemDetails = null;
+ // Attempt to deserialize the response content to ProblemDetailsDto if the request fails.
+ try
{
- // Handle empty content case.
- if (string.IsNullOrEmpty(content))
- return default!;
- return JsonSerializer.Deserialize(content, _jsonOptions)!;
- }
- else
- {
- ProblemDetailsDto? problemDetails = null;
- // Attempt to deserialize the response content to ProblemDetailsDto if the request fails.
- try
- {
- problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
- }
- catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ }
- throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath);
+ problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
}
+ catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ }
+ return new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath);
}
///
diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs
index 77bae8cd..ea76db0c 100644
--- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs
+++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
+using Lumina.Presentation.Web.Common.Exceptions;
using System.Collections.Generic;
using System.IO;
using System.Threading;
@@ -20,6 +21,7 @@ public interface IApiHttpClient
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the GET request.
+ /// Thrown when the API returns an unsuccessful response.
Task GetAsync(string endpoint, CancellationToken cancellationToken = default);
///
@@ -36,25 +38,38 @@ public interface IApiHttpClient
///
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
- /// A model containing the deserialized blob.
+ /// A model containing the raw blob bytes and their content type.
+ /// Thrown when the API returns an unsuccessful response.
Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default);
///
- /// Sends a DELETE request to the specified as an asynchronous operation.
+ /// Sends a DELETE request to the specified as an asynchronous operation, discarding the response content.
///
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
+ /// Thrown when the API returns an unsuccessful response.
Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default);
+ ///
+ /// Sends a PUT request to the specified as an asynchronous operation, discarding the response content.
+ ///
+ /// The expected type of the payload content.
+ /// The API endpoint where the request is being sent.
+ /// The data to be serialized and sent to the API.
+ /// Cancellation token that can be used to stop the execution.
+ /// Thrown when the API returns an unsuccessful response.
+ Task PutIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default);
+
///
/// Sends a PUT request to the specified as an asynchronous operation and returns the result.
///
/// The expected type of the response content.
/// The expected type of the payload content.
/// The API endpoint where the request is being sent.
- /// The data to be serialized and send to the API.
+ /// The data to be serialized and sent to the API.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the PUT request.
+ /// Thrown when the API returns an unsuccessful response.
Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default);
///
@@ -67,6 +82,7 @@ public interface IApiHttpClient
/// The name of the form field carrying the file.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the PUT request.
+ /// Thrown when the API returns an unsuccessful response.
Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default);
///
@@ -79,8 +95,37 @@ public interface IApiHttpClient
/// The name of the form field carrying the file.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the POST request.
+ /// Thrown when the API returns an unsuccessful response.
Task PostMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default);
+ ///
+ /// Sends a POST request without a payload to the specified as an asynchronous operation, discarding the response content.
+ ///
+ /// The API endpoint where the request is being sent.
+ /// Cancellation token that can be used to stop the execution.
+ /// Thrown when the API returns an unsuccessful response.
+ Task PostIgnoringResponseAsync(string endpoint, CancellationToken cancellationToken = default);
+
+ ///
+ /// Sends a POST request without a payload to the specified as an asynchronous operation and returns the result.
+ ///
+ /// The expected type of the response content.
+ /// The API endpoint where the request is being sent.
+ /// Cancellation token that can be used to stop the execution.
+ /// The deserialized response containing the result of the POST request.
+ /// Thrown when the API returns an unsuccessful response.
+ Task PostAsync(string endpoint, CancellationToken cancellationToken = default);
+
+ ///
+ /// Sends a POST request to the specified as an asynchronous operation, discarding the response content.
+ ///
+ /// The expected type of the payload content.
+ /// The API endpoint where the request is being sent.
+ /// The data to be serialized and sent to the API.
+ /// Cancellation token that can be used to stop the execution.
+ /// Thrown when the API returns an unsuccessful response.
+ Task PostIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default);
+
///
/// Sends a POST request to the specified as an asynchronous operation and returns the result.
///
@@ -90,5 +135,6 @@ public interface IApiHttpClient
/// The data to be serialized and sent to the API.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the POST request.
+ /// Thrown when the API returns an unsuccessful response.
Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default);
}
diff --git a/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs
index b4f61abd..5a407ea8 100644
--- a/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs
+++ b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs
@@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http;
using Polly.CircuitBreaker;
using System;
using System.Linq;
+using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
@@ -74,6 +75,13 @@ public class AuthorizationService : IAuthorizationService
{
return await _apiHttpClient.GetAsync($"auth/get-authorization?userId={Uri.EscapeDataString(userId)}", cancellationToken);
}
+ catch (ApiException exception) when (exception.HttpStatusCode == HttpStatusCode.NotFound)
+ {
+ // This is the only place that knows the request was the current-user authorization check. Convert a 404 here into an explicit exception, so the middleware can
+ // invalidate the stale session without guessing from the request path. Do not move this classification into the middleware: it only sees a generic ApiException,
+ // and a caller-controlled path can contain the authorization route text.
+ throw new CurrentUserAuthorizationException(exception.ProblemDetails, exception.HttpStatusCode, exception.RequestPath);
+ }
catch (Exception exception)
{
HttpContext? httpContext = _httpContextAccessor.HttpContext;
diff --git a/src/Lumina.Presentation.Web/Common/Exceptions/CurrentUserAuthorizationException.cs b/src/Lumina.Presentation.Web/Common/Exceptions/CurrentUserAuthorizationException.cs
new file mode 100644
index 00000000..475e0438
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Exceptions/CurrentUserAuthorizationException.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Common;
+using System.Net;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Exceptions;
+
+///
+/// Exception for an unsuccessful current-user authorization check, which means that the stored session refers to a user the API no longer knows.
+///
+public class CurrentUserAuthorizationException : ApiException
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The problem details object returned by the API.
+ /// The HTTP status code returned by the API.
+ /// The absolute path of the API endpoint that produced this exception.
+ public CurrentUserAuthorizationException(ProblemDetailsDto? problemDetails, HttpStatusCode httpStatusCode, string? requestPath = null)
+ : base(problemDetails, httpStatusCode, requestPath)
+ {
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs
index 6035e7c3..9ffee6e2 100644
--- a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs
+++ b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs
@@ -137,9 +137,10 @@ public class ExceptionHandlingMiddleware
///
private async Task HandleNotFoundAsync(HttpContext context, ApiException apiException)
{
- // When the API reports the currently logged-in user no longer exists (404 from the current-user authorization check),
- // the stored session is stale: sign out and send the user to the login page instead of the not-found page.
- if (context.User?.Identity?.IsAuthenticated == true && IsCurrentUserAuthorizationCheck(apiException))
+ // When the API reports the currently logged-in user no longer exists, the stored session is stale: sign out and send the user
+ // to the login page instead of the not-found page. The condition is signaled by the authorization check itself, never inferred
+ // from the URL of the failed request, because a caller-controlled path can contain the same text.
+ if (context.User?.Identity?.IsAuthenticated == true && apiException is CurrentUserAuthorizationException)
{
await HandleUnauthorizedAsync(context).ConfigureAwait(false);
return;
@@ -412,13 +413,4 @@ public class ExceptionHandlingMiddleware
}
}
- ///
- /// Determines whether the API exception originated from the authorization check of the currently logged in user.
- ///
- /// The API exception to inspect.
- /// if the exception came from the current-user authorization endpoint, otherwise.
- private static bool IsCurrentUserAuthorizationCheck(ApiException apiException)
- {
- return apiException.RequestPath?.Contains("/auth/get-authorization", StringComparison.OrdinalIgnoreCase) == true;
- }
}
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Common/EmptyRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Common/EmptyRequest.cs
deleted file mode 100644
index 12334e34..00000000
--- a/src/Lumina.Presentation.Web/Common/Requests/Common/EmptyRequest.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-namespace Lumina.Presentation.Web.Common.Requests.Common;
-
-///
-/// Record used for empty requests and responses.
-///
-public record struct EmptyRequest();
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs
index 0688c4c9..1ea93ac4 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class FireScheduledJobEndpoint : BaseEndpointCancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(FireScheduledJobRequest request, CancellationToken cancellationToken)
{
- await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs
index fa6988a2..13808829 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class StartScheduledJobEndpoint : BaseEndpointCancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(StartScheduledJobRequest request, CancellationToken cancellationToken)
{
- await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs
index 55616f57..6f0f1b57 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class StopScheduledJobEndpoint : BaseEndpointCancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(StopScheduledJobRequest request, CancellationToken cancellationToken)
{
- await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs
index 03075603..20147765 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class UpdateSchedulerDisplayPreferencesEndpoint : BaseEndpointCancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(UpdateSchedulerDisplayPreferencesRequest request, CancellationToken cancellationToken)
{
- await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, request, cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs
index 3d6b6fc0..b2ea8777 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Enums.Favorites;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -16,7 +15,7 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
///
/// API endpoint for the /{culture}/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite route.
///
-public class RemoveFavoriteEndpoint : BaseEndpoint
+public class RemoveFavoriteEndpoint : BaseEndpoint
{
// A value that is not a name of FavoriteMediaKind, so the API rejects a crafted route value with its own validation error.
private const string INVALID_MEDIA_KIND_PLACEHOLDER = "Invalid";
@@ -50,7 +49,7 @@ public class RemoveFavoriteEndpoint : BaseEndpoint
/// The request object.
/// Cancellation token that can be used to stop the execution.
- public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// The route values are normalized before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment.
// The media kind must be the name of a FavoriteMediaKind member, which also rejects numeric strings and comma separated flag lists, and the Id must be a Guid.
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs
index 5a8b036a..957d2e8f 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -57,9 +56,8 @@ public class RestoreMusicAlbumEndpoint : BaseEndpoint
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
- await _apiHttpClient.PostAsync(
+ await _apiHttpClient.PostIgnoringResponseAsync(
ApiRoutes.Music.RESTORE_ALBUM.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId).Replace("{albumId}", albumId),
- new Web.Common.Requests.Common.EmptyRequest(),
cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isRestored = true });
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpoint.cs
index 6016f71e..c114a88f 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpoint.cs
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -55,9 +54,8 @@ public class RestoreMusicArtistEndpoint : BaseEndpoint
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
- await _apiHttpClient.PostAsync(
+ await _apiHttpClient.PostIgnoringResponseAsync(
ApiRoutes.Music.RESTORE_ARTIST.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId),
- new Web.Common.Requests.Common.EmptyRequest(),
cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isRestored = true });
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs
index e79985a0..de51e0da 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -59,9 +58,8 @@ public class RestoreMusicTrackEndpoint : BaseEndpoint
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
- await _apiHttpClient.PostAsync(
+ await _apiHttpClient.PostIgnoringResponseAsync(
ApiRoutes.Music.RESTORE_TRACK.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId).Replace("{albumId}", albumId).Replace("{trackId}", trackId),
- new Web.Common.Requests.Common.EmptyRequest(),
cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isRestored = true });
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs
index d5aa5b83..3ee6e871 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -47,7 +46,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint
/// Cancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
- await _apiHttpClient.PostAsync(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN, new Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PostIgnoringResponseAsync(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs
index 66b4def9..578354f4 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -48,7 +47,7 @@ public class CancelLibraryScanEndpoint : BaseEndpointCancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken)
{
- await _apiHttpClient.PostAsync(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{scanId}", request.ScanId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PostIgnoringResponseAsync(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{scanId}", request.ScanId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs
index 7c77f6f0..5493f7c1 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -48,7 +47,7 @@ public class ScanLibrariesEndpoint : BaseEndpoint
/// Cancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
- ScanLibraryDto[] response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARIES, new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
+ ScanLibraryDto[] response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARIES, cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs
index 19484e1c..1410f30d 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -49,7 +48,7 @@ public class ScanLibraryEndpoint : BaseEndpoint
/// Cancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken)
{
- ScanLibraryDto response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARY.Replace("{id}", request.Id.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
+ ScanLibraryDto response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARY.Replace("{id}", request.Id.ToString()), cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs
index 79203ddf..2e4b7de2 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -56,9 +55,8 @@ public class RestoreBookEndpoint : BaseEndpoint
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
- await _apiHttpClient.PostAsync(
+ await _apiHttpClient.PostIgnoringResponseAsync(
ApiRoutes.Books.RESTORE_BOOK.Replace("{libraryId}", libraryId).Replace("{bookId}", bookId),
- new Web.Common.Requests.Common.EmptyRequest(),
cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isRestored = true });
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs
index 1023d1a9..7a573cd9 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -72,7 +71,7 @@ public class StartConsumptionEndpoint : BaseEndpoint
.Replace("{libraryId}", libraryId, StringComparison.Ordinal)
.Replace("{mediaKind}", mediaKind, StringComparison.Ordinal)
.Replace("{mediaItemId}", mediaItemId, StringComparison.Ordinal);
- ConsumptionRecordDto record = await _apiHttpClient.PostAsync(endpoint, request, cancellationToken).ConfigureAwait(false);
+ ConsumptionRecordDto record = await _apiHttpClient.PostAsync(endpoint, cancellationToken).ConfigureAwait(false);
return JsonSuccess(record);
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs
index 9fb09752..899edfd1 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -15,7 +14,7 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist;
///
/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-delete-playlist route.
///
-public class DeletePlaylistEndpoint : BaseEndpoint
+public class DeletePlaylistEndpoint : BaseEndpoint
{
private readonly IApiHttpClient _apiHttpClient;
@@ -46,7 +45,7 @@ public class DeletePlaylistEndpoint : BaseEndpoint
/// The request object.
/// Cancellation token that can be used to stop the execution.
- public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape its URL segment.
string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty;
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs
index 3931a8ff..9e47e0b3 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class UpdatePluginSettingsEndpoint : BaseEndpointCancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(UpdatePluginSettingsRequest request, CancellationToken cancellationToken)
{
- await _apiHttpClient.PutAsync(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs
index 8c0be3be..6d0ec20a 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -48,7 +47,7 @@ public class UpdatePlaybackStateEndpoint : BaseEndpointCancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(PlaybackStateDto request, CancellationToken cancellationToken)
{
- await _apiHttpClient.PutAsync(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isUpdated = true });
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs
index 1dd83b01..b3e8f74d 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.UsersManagement;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Common;
-using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Security.Claims;
@@ -54,7 +53,7 @@ public class UpdateUserSettingsEndpoint : BaseEndpoint
/// Cancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(UserSettingsDto request, CancellationToken cancellationToken)
{
- await _apiHttpClient.PutAsync(ApiRoutes.Users.UPDATE_USER_SETTINGS, request, cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.Users.UPDATE_USER_SETTINGS, request, cancellationToken).ConfigureAwait(false);
// Keep the per-user theme cache preference in sync with the stored settings, so the handler applies it immediately.
Guid? userId = GetCurrentUserId();
diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs
index 42ff8bb0..da63cf7b 100644
--- a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs
+++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs
@@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Enums.Themes;
+using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using System.Collections.Generic;
using System.IO;
@@ -68,7 +69,7 @@ public sealed class ThemeService
/// Cancellation token that can be used to stop the execution.
public async Task SetCurrentThemeAsync(string themeId, CancellationToken cancellationToken = default)
{
- await _apiHttpClient.PutAsync(ApiRoutes.Themes.SET_CURRENT_THEME, new { ThemeId = themeId }, cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.Themes.SET_CURRENT_THEME, new SetCurrentThemeRequest(themeId), cancellationToken).ConfigureAwait(false);
}
///
@@ -101,7 +102,7 @@ public sealed class ThemeService
/// Cancellation token that can be used to stop the execution.
public async Task RestoreThemeAsync(string themeId, CancellationToken cancellationToken = default)
{
- await _apiHttpClient.PostAsync(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), new { }, cancellationToken).ConfigureAwait(false);
+ await _apiHttpClient.PostIgnoringResponseAsync(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false);
}
///
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs
index ac9c82b8..dd6db315 100644
--- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs
@@ -27,9 +27,15 @@ public class StubApiHttpClient : IApiHttpClient
private readonly Dictionary> _getResponseFactories = [];
private readonly Dictionary> _postResponseFactories = [];
private readonly Dictionary> _putResponseFactories = [];
+ private readonly Dictionary _postExceptions = [];
+ private readonly Dictionary _putExceptions = [];
+ private readonly HashSet _postBodylessSuccessEndpoints = [];
+ private readonly Dictionary _postPayloadTypes = [];
+ private readonly Dictionary _putPayloadTypes = [];
private readonly HashSet _deleteSuccessEndpoints = [];
private readonly Dictionary _deleteExceptions = [];
private BlobDataDto? _blobResponse;
+ private ApiException? _blobException;
///
/// Gets the authorization response returned for the auth/get-authorization endpoint.
@@ -121,7 +127,7 @@ public class StubApiHttpClient : IApiHttpClient
/// The exception to throw.
public void RegisterPostException(string endpoint, ApiException exception)
{
- _postResponseFactories[endpoint] = _ => throw exception;
+ _postExceptions[endpoint] = exception;
}
///
@@ -141,7 +147,7 @@ public class StubApiHttpClient : IApiHttpClient
/// The exception to throw.
public void RegisterPutException(string endpoint, ApiException exception)
{
- _putResponseFactories[endpoint] = _ => throw exception;
+ _putExceptions[endpoint] = exception;
}
///
@@ -193,6 +199,44 @@ public class StubApiHttpClient : IApiHttpClient
_blobResponse = blob;
}
+ ///
+ /// Registers the exception thrown when a blob endpoint is called.
+ ///
+ /// The exception to throw.
+ public void RegisterBlobException(ApiException exception)
+ {
+ _blobException = exception;
+ }
+
+ ///
+ /// Registers the specified POST endpoint as accepting a bodyless request without returning a response body.
+ ///
+ /// The API endpoint for which to register success.
+ public void RegisterPostSuccess(string endpoint)
+ {
+ _postBodylessSuccessEndpoints.Add(endpoint);
+ }
+
+ ///
+ /// Registers the specified POST endpoint as accepting a payload of type without returning a response body.
+ ///
+ /// The expected type of the payload content.
+ /// The API endpoint for which to register the payload type.
+ public void RegisterPostPayload(string endpoint)
+ {
+ _postPayloadTypes[endpoint] = typeof(TModel);
+ }
+
+ ///
+ /// Registers the specified PUT endpoint as accepting a payload of type without returning a response body.
+ ///
+ /// The expected type of the payload content.
+ /// The API endpoint for which to register the payload type.
+ public void RegisterPutPayload(string endpoint)
+ {
+ _putPayloadTypes[endpoint] = typeof(TModel);
+ }
+
///
/// Resets all registered responses and captured requests, keeping only the default responses.
///
@@ -201,9 +245,15 @@ public class StubApiHttpClient : IApiHttpClient
_getResponseFactories.Clear();
_postResponseFactories.Clear();
_putResponseFactories.Clear();
+ _postExceptions.Clear();
+ _putExceptions.Clear();
+ _postBodylessSuccessEndpoints.Clear();
+ _postPayloadTypes.Clear();
+ _putPayloadTypes.Clear();
_deleteSuccessEndpoints.Clear();
_deleteExceptions.Clear();
_blobResponse = null;
+ _blobException = null;
AuthorizationException = null;
GetEndpointsCalled.Clear();
PostRequests.Clear();
@@ -252,9 +302,11 @@ public class StubApiHttpClient : IApiHttpClient
///
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
- /// A model containing the deserialized blob.
+ /// A model containing the raw blob bytes and their content type.
public Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default)
{
+ if (_blobException is not null)
+ throw _blobException;
if (_blobResponse is not null)
return Task.FromResult(_blobResponse);
throw new NotSupportedException("Blob retrieval is not supported by the test stub.");
@@ -275,18 +327,37 @@ public class StubApiHttpClient : IApiHttpClient
throw new ApiException(null, System.Net.HttpStatusCode.InternalServerError, endpoint);
}
+ ///
+ /// Sends a PUT request to the specified as an asynchronous operation, discarding the response content.
+ ///
+ /// The expected type of the payload content.
+ /// The API endpoint where the request is being sent.
+ /// The data to be serialized and sent to the API.
+ /// Cancellation token that can be used to stop the execution.
+ public Task PutIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default)
+ {
+ PutRequests.Add((endpoint, data));
+ if (_putExceptions.TryGetValue(endpoint, out ApiException? exception))
+ throw exception;
+ if (_putPayloadTypes.TryGetValue(endpoint, out Type? expectedType) && expectedType == typeof(TModel))
+ return Task.CompletedTask;
+ throw new InvalidOperationException($"No PUT payload of type '{typeof(TModel).Name}' is registered for the endpoint '{endpoint}'.");
+ }
+
///
/// Sends a PUT request to the specified as an asynchronous operation and returns the result.
///
/// The expected type of the response content.
/// The expected type of the payload content.
/// The API endpoint where the request is being sent.
- /// The data to be serialized and send to the API.
+ /// The data to be serialized and sent to the API.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the PUT request.
public Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default)
{
PutRequests.Add((endpoint, data));
+ if (_putExceptions.TryGetValue(endpoint, out ApiException? exception))
+ throw exception;
if (_putResponseFactories.TryGetValue(endpoint, out Func