Skip to content

Close Fluent Validation For controller #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 30, 2022
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
3 changes: 2 additions & 1 deletion backend/ServiceSimulation/Api/Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@

<ItemGroup>
<PackageReference Include="AutoMapper" Version="11.0.1" />
<PackageReference Include="FluentValidation" Version="10.4.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="10.4.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="10.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.1" />
</ItemGroup>
Expand All @@ -17,7 +19,6 @@
<Folder Include="Controllers\" />
<Folder Include="Entities\" />
<Folder Include="Configuration\" />
<Folder Include="Extensions\" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 4 additions & 0 deletions backend/ServiceSimulation/Api/Controllers/Simulation.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using Api.Entities;
using Api.Validation;
using AutoMapper;
using Bll.Domain.Interfaces;
using Bll.Domain.Models;
using FluentValidation;
using Microsoft.AspNetCore.Mvc;

namespace Api.Controllers;
Expand Down Expand Up @@ -30,6 +32,8 @@ public Simulation(ISimulationService simulationService,
[HttpGet("/start")]
public IActionResult Start(InputParameters parameters)
{
new InputParametersValidator().ValidateAndThrow(parameters);

_simulationService.StartSimulation(parameters);
var endResultsOfModeling = _resultManager.CalculateResultsOfModeling();
var apiResults = _mapper.Map<ApiResults>((endResultsOfModeling, _results));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Api.Middlewares;

namespace Api.Extensions
{
public static class CustomExceptionHandlerMiddlewareExtensions
{
public static IApplicationBuilder UseCustomExceptionHandler(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomExceptionHandlerMiddleware>();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System.Net;
using System.Text.Json;
using FluentValidation;

namespace Api.Middlewares
{
public class CustomExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;

// private readonly ILogger _logger;
public CustomExceptionHandlerMiddleware(RequestDelegate next)//,
// ILogger<CustomExceptionHandlerMiddleware> logger)
{
_next = next;
//_logger = logger;
}

public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}

private Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var statusCode = HttpStatusCode.InternalServerError;
var result = string.Empty;

switch (ex)
{
case ValidationException validationException:
statusCode = HttpStatusCode.BadRequest;
result = JsonSerializer.Serialize(validationException.Errors);
//_logger.LogDebug(validationException.Message);
break;

default:
statusCode = HttpStatusCode.NotFound;
break;

}
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)statusCode;

if (result == string.Empty)
{
result = JsonSerializer.Serialize(new { error = ex.Message });
}
return context.Response.WriteAsync(result);
}
}
}
10 changes: 9 additions & 1 deletion backend/ServiceSimulation/Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
using Api.Configuration;
using Api.Extensions;
using Api.Validation;
using Bll.Domain.Entities;
using Bll.Domain.Factories;
using Bll.Domain.Interfaces;
using Bll.Domain.Models;
using Bll.Domain.Services;
using FluentValidation;
using FluentValidation.AspNetCore;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers().AddFluentValidation(fv =>
{
fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
//fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
fv.RegisterValidatorsFromAssemblyContaining<InputParametersValidator>();
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
Expand All @@ -28,6 +32,8 @@
builder.Services.AddTransient<IBufferManagerFactory, BufferManagerFactory>();
builder.Services.AddTransient<IDeviceManager, DeviceManager>();
builder.Services.AddTransient<ISourceManager, SourceManager>();

builder.Services.AddTransient<IValidator<InputParameters>, InputParametersValidator>();
#endregion

#region Mapper
Expand All @@ -50,6 +56,8 @@
app.UseSwaggerUI();
}

app.UseCustomExceptionHandler();

app.UseHttpsRedirection();

app.UseAuthorization();
Expand Down