mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 14:11:10 +00:00
Swiches Client Web app from Blazor to ASP.NET Core MVC
This commit is contained in:
1 parent
cf94676666
commit
9a7d4c607d
35 files changed
+4066
-1853
No files matched your search
+12
-8
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Filters;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Services.UI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -11,6 +13,7 @@ using Polly.Wrap;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DependencyInjection;
|
||||
@@ -28,25 +31,25 @@ public static class PresentationWebLayerServices
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services)
|
||||
{
|
||||
services.AddControllersWithViews();
|
||||
services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter)))
|
||||
.AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
|
||||
|
||||
// scan the current assembly for validators and register them to the DI container
|
||||
services.AddValidatorsFromAssemblyContaining<Program>(ServiceLifetime.Singleton);
|
||||
|
||||
// handle transient errors like network timeouts or intermittent failures
|
||||
AsyncRetryPolicy<HttpResponseMessage> retryPolicy = Policy
|
||||
AsyncRetryPolicy<HttpResponseMessage> retryPolicy = Policy<HttpResponseMessage>
|
||||
.Handle<HttpRequestException>()
|
||||
.OrResult<HttpResponseMessage>(r =>
|
||||
!r.IsSuccessStatusCode &&
|
||||
r.StatusCode != HttpStatusCode.Forbidden &&
|
||||
r.StatusCode != HttpStatusCode.BadRequest)
|
||||
.OrInner<ApiException>(ex =>
|
||||
ex.HttpStatusCode != HttpStatusCode.BadRequest &&
|
||||
ex.HttpStatusCode != HttpStatusCode.Forbidden)
|
||||
.WaitAndRetryAsync(3, retryAttempt =>
|
||||
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
|
||||
|
||||
// use a circuit breaker to prevent repeatedly calling a failing service
|
||||
AsyncCircuitBreakerPolicy<HttpResponseMessage> circuitBreakerPolicy = Policy
|
||||
AsyncCircuitBreakerPolicy<HttpResponseMessage> circuitBreakerPolicy = Policy<HttpResponseMessage>
|
||||
.Handle<HttpRequestException>()
|
||||
.OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.InternalServerError)
|
||||
.OrInner<ApiException>(ex => ex.HttpStatusCode == HttpStatusCode.InternalServerError)
|
||||
.CircuitBreakerAsync(3, TimeSpan.FromSeconds(30));
|
||||
|
||||
AsyncPolicyWrap<HttpResponseMessage> policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
|
||||
@@ -58,6 +61,7 @@ public static class PresentationWebLayerServices
|
||||
|
||||
services.AddSingleton<ComboboxService>();
|
||||
services.AddScoped<INotificationService, NotificationService>();
|
||||
services.AddScoped<ApiExceptionFilter>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Filters;
|
||||
|
||||
/// <summary>
|
||||
/// Filters API exceptions and provides centralized handling for API-related errors.
|
||||
/// </summary>
|
||||
public class ApiExceptionFilter : IExceptionFilter
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Called after an action has thrown an Exception.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="ExceptionContext"/>.</param>
|
||||
public void OnException(ExceptionContext context)
|
||||
{
|
||||
// check if the exception is an ApiException
|
||||
if (context.Exception is ApiException apiException)
|
||||
{
|
||||
// handle unauthorized errors by prompting the user to re-login
|
||||
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
SignOutSynchronously(context.HttpContext);
|
||||
string currentUrl = context.HttpContext.Request.GetDisplayUrl();
|
||||
context.HttpContext.Response.Redirect(currentUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
|
||||
}
|
||||
else
|
||||
{
|
||||
StringBuilder errorMessage = new();
|
||||
if (apiException.ProblemDetails is not null)
|
||||
{
|
||||
errorMessage.AppendLine($"HTTP {apiException.ProblemDetails.Status} {apiException.HttpStatusCode}<br>");
|
||||
if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail))
|
||||
errorMessage.AppendLine($"<b>{apiException.ProblemDetails.Detail}<b>");
|
||||
else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title))
|
||||
errorMessage.AppendLine($"<b>{apiException.ProblemDetails.Title}<b>");
|
||||
if (apiException.ProblemDetails.Extensions is not null && apiException.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj))
|
||||
{
|
||||
if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
errorMessage.AppendLine("Validation Errors:");
|
||||
foreach (JsonProperty error in jsonElement.EnumerateObject())
|
||||
{
|
||||
string fieldName = error.Name;
|
||||
if (error.Value.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement errorValue in error.Value.EnumerateArray())
|
||||
errorMessage.AppendLine($"- {fieldName}: {errorValue}<br>");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (apiException.ProblemDetails.Extensions is not null)
|
||||
foreach (KeyValuePair<string, JsonElement> extension in apiException.ProblemDetails.Extensions)
|
||||
if (extension.Key != "errors")
|
||||
errorMessage.AppendLine($"{extension.Key}: {extension.Value}<br>");
|
||||
}
|
||||
else
|
||||
{
|
||||
errorMessage.AppendLine($"HTTP {apiException.HttpStatusCode}<br>");
|
||||
errorMessage.AppendLine($"{apiException.Message}<br>");
|
||||
}
|
||||
// return a JSON result with the error details
|
||||
context.Result = new JsonResult(new
|
||||
{
|
||||
success = false,
|
||||
errorMessage = errorMessage.ToString()
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// return a JSON result with the error details
|
||||
context.Result = new JsonResult(new
|
||||
{
|
||||
success = false,
|
||||
errorMessage = context.Exception.Message.ToString()
|
||||
});
|
||||
}
|
||||
// mark the exception as handled to prevent propagation
|
||||
context.ExceptionHandled = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signs out the user synchronously by deleting the authentication cookie and token.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HttpContext for the current request.</param>
|
||||
private static void SignOutSynchronously(HttpContext httpContext)
|
||||
{
|
||||
Task task = httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
task.Wait(); // run the task synchronously
|
||||
httpContext.Response.Cookies.Delete("Token");
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
namespace Lumina.Presentation.Web.Common.Models.FileManagement;
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Models.FileManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response containing a file system path.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Path}")]
|
||||
public class PathSegmentModel
|
||||
{
|
||||
#region ==================================================================== PROPERTIES =================================================================================
|
||||
@@ -11,4 +16,4 @@ public class PathSegmentModel
|
||||
/// </summary>
|
||||
public string Path { get; set; } = null!;
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user