Skip to content

Commit dd5bfc1

Browse files
authored
Merge pull request #21 from NiceOneFox/T16_FluentValidation_For_Controller
Close Fluent Validation For controller
2 parents af8f199 + 542e18f commit dd5bfc1

File tree

5 files changed

+86
-2
lines changed

5 files changed

+86
-2
lines changed

backend/ServiceSimulation/Api/Api.csproj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88

99
<ItemGroup>
1010
<PackageReference Include="AutoMapper" Version="11.0.1" />
11+
<PackageReference Include="FluentValidation" Version="10.4.0" />
1112
<PackageReference Include="FluentValidation.AspNetCore" Version="10.4.0" />
13+
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="10.4.0" />
1214
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
1315
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.1" />
1416
</ItemGroup>
@@ -17,7 +19,6 @@
1719
<Folder Include="Controllers\" />
1820
<Folder Include="Entities\" />
1921
<Folder Include="Configuration\" />
20-
<Folder Include="Extensions\" />
2122
</ItemGroup>
2223

2324
<ItemGroup>

backend/ServiceSimulation/Api/Controllers/Simulation.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
using Api.Entities;
2+
using Api.Validation;
23
using AutoMapper;
34
using Bll.Domain.Interfaces;
45
using Bll.Domain.Models;
6+
using FluentValidation;
57
using Microsoft.AspNetCore.Mvc;
68

79
namespace Api.Controllers;
@@ -30,6 +32,8 @@ public Simulation(ISimulationService simulationService,
3032
[HttpGet("/start")]
3133
public IActionResult Start(InputParameters parameters)
3234
{
35+
new InputParametersValidator().ValidateAndThrow(parameters);
36+
3337
_simulationService.StartSimulation(parameters);
3438
var endResultsOfModeling = _resultManager.CalculateResultsOfModeling();
3539
var apiResults = _mapper.Map<ApiResults>((endResultsOfModeling, _results));
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
using Api.Middlewares;
2+
3+
namespace Api.Extensions
4+
{
5+
public static class CustomExceptionHandlerMiddlewareExtensions
6+
{
7+
public static IApplicationBuilder UseCustomExceptionHandler(this IApplicationBuilder builder)
8+
{
9+
return builder.UseMiddleware<CustomExceptionHandlerMiddleware>();
10+
}
11+
}
12+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
using System.Net;
2+
using System.Text.Json;
3+
using FluentValidation;
4+
5+
namespace Api.Middlewares
6+
{
7+
public class CustomExceptionHandlerMiddleware
8+
{
9+
private readonly RequestDelegate _next;
10+
11+
// private readonly ILogger _logger;
12+
public CustomExceptionHandlerMiddleware(RequestDelegate next)//,
13+
// ILogger<CustomExceptionHandlerMiddleware> logger)
14+
{
15+
_next = next;
16+
//_logger = logger;
17+
}
18+
19+
public async Task Invoke(HttpContext context)
20+
{
21+
try
22+
{
23+
await _next(context);
24+
}
25+
catch (Exception ex)
26+
{
27+
await HandleExceptionAsync(context, ex);
28+
}
29+
}
30+
31+
private Task HandleExceptionAsync(HttpContext context, Exception ex)
32+
{
33+
var statusCode = HttpStatusCode.InternalServerError;
34+
var result = string.Empty;
35+
36+
switch (ex)
37+
{
38+
case ValidationException validationException:
39+
statusCode = HttpStatusCode.BadRequest;
40+
result = JsonSerializer.Serialize(validationException.Errors);
41+
//_logger.LogDebug(validationException.Message);
42+
break;
43+
44+
default:
45+
statusCode = HttpStatusCode.NotFound;
46+
break;
47+
48+
}
49+
context.Response.ContentType = "application/json";
50+
context.Response.StatusCode = (int)statusCode;
51+
52+
if (result == string.Empty)
53+
{
54+
result = JsonSerializer.Serialize(new { error = ex.Message });
55+
}
56+
return context.Response.WriteAsync(result);
57+
}
58+
}
59+
}

backend/ServiceSimulation/Api/Program.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
11
using Api.Configuration;
22
using Api.Extensions;
3+
using Api.Validation;
34
using Bll.Domain.Entities;
45
using Bll.Domain.Factories;
56
using Bll.Domain.Interfaces;
7+
using Bll.Domain.Models;
68
using Bll.Domain.Services;
9+
using FluentValidation;
710
using FluentValidation.AspNetCore;
811
using System.Reflection;
912

1013
var builder = WebApplication.CreateBuilder(args);
1114

1215
builder.Services.AddControllers().AddFluentValidation(fv =>
1316
{
14-
fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
17+
//fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
18+
fv.RegisterValidatorsFromAssemblyContaining<InputParametersValidator>();
1519
});
1620
builder.Services.AddEndpointsApiExplorer();
1721
builder.Services.AddSwaggerGen();
@@ -28,6 +32,8 @@
2832
builder.Services.AddTransient<IBufferManagerFactory, BufferManagerFactory>();
2933
builder.Services.AddTransient<IDeviceManager, DeviceManager>();
3034
builder.Services.AddTransient<ISourceManager, SourceManager>();
35+
36+
builder.Services.AddTransient<IValidator<InputParameters>, InputParametersValidator>();
3137
#endregion
3238

3339
#region Mapper
@@ -50,6 +56,8 @@
5056
app.UseSwaggerUI();
5157
}
5258

59+
app.UseCustomExceptionHandler();
60+
5361
app.UseHttpsRedirection();
5462

5563
app.UseAuthorization();

0 commit comments

Comments
 (0)