diff --git a/Project.App/Project.Api/Infrastructure/ConcurrencyExceptionFilter.cs b/Project.App/Project.Api/Infrastructure/ConcurrencyExceptionFilter.cs new file mode 100644 index 0000000..0be7cf6 --- /dev/null +++ b/Project.App/Project.Api/Infrastructure/ConcurrencyExceptionFilter.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.EntityFrameworkCore; + +namespace Project.Api.Infrastructure; + +public sealed class ConcurrencyExceptionFilter : IExceptionFilter +{ + private readonly ILogger _logger; + public ConcurrencyExceptionFilter(ILogger logger) => _logger = logger; + + public void OnException(ExceptionContext context) + { + if (context.Exception is DbUpdateConcurrencyException ex) + { + _logger.LogWarning(ex, "Optimistic concurrency conflict detected."); + + var problem = new ConcurrencyProblemDetails( + "The resource changed since you last fetched it. Fetch the latest version and try again."); + + context.Result = new ObjectResult(problem) { StatusCode = problem.Status }; + context.ExceptionHandled = true; // prevent default 500 + } + } +} +//try commit again +//more comments \ No newline at end of file diff --git a/Project.App/Project.Api/Infrastructure/ConcurrencyProblemDetails.cs b/Project.App/Project.Api/Infrastructure/ConcurrencyProblemDetails.cs new file mode 100644 index 0000000..cc1b4a3 --- /dev/null +++ b/Project.App/Project.Api/Infrastructure/ConcurrencyProblemDetails.cs @@ -0,0 +1,17 @@ +using Microsoft.AspNetCore.Mvc; + +namespace Project.Api.Infrastructure; + +public sealed class ConcurrencyProblemDetails : ProblemDetails +{ + public ConcurrencyProblemDetails(string? detail = null) + { + var x = 4; + Title = "Update conflict"; + Status = StatusCodes.Status409Conflict; + Type = "https://httpstatuses.com/409"; + Detail = detail ?? "The resource was modified by another request. Please refresh and retry."; + } +} +//try commit again +//more comments \ No newline at end of file diff --git a/Project.App/Project.Api/Program.cs b/Project.App/Project.Api/Program.cs index 15c77aa..d563be2 100644 --- a/Project.App/Project.Api/Program.cs +++ b/Project.App/Project.Api/Program.cs @@ -8,6 +8,7 @@ using Project.Api.Services.Interface; using Project.Api.Utilities.Middleware; using Serilog; +using Project.Api.Infrastructure; namespace Project.Api; @@ -43,6 +44,11 @@ public static void Main(string[] args) builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); + //Infrastructure - add concurrency exception filter globally///added here + // Add exception filter to handle concurrency exceptions globally + builder.Services.AddControllers(o =>{ + o.Filters.Add();}); + var app = builder.Build(); app.UseMiddleware();