Spaces:
Runtime error
Runtime error
Download src/SCM.Api/Program.cs from rafaeldavila/scm-api: direct link, hf CLI and curl.
- Browser
- Download file 6.62 kB
-
https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Api/Program.cs
- Command line
-
hf download hf://spaces/rafaeldavila/scm-api/src/SCM.Api/Program.cs
-
curl -L -o Program.cs https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Api/Program.cs
6.62 kB
| using System.Reflection; | |
| using System.Text; | |
| using System.Text.Json.Serialization; | |
| using Asp.Versioning; | |
| using Microsoft.AspNetCore.Authentication.JwtBearer; | |
| using Microsoft.IdentityModel.Tokens; | |
| using Microsoft.OpenApi.Models; | |
| using SCM.Api.Filters; | |
| using SCM.Api.Middleware; | |
| using SCM.Application; | |
| using SCM.Infrastructure; | |
| using SCM.Infrastructure.Security; | |
| using SCM.Integrations; | |
| using SCM.Migrations; | |
| using Serilog; | |
| Log.Logger = new LoggerConfiguration() | |
| .WriteTo.Console() | |
| .CreateBootstrapLogger(); | |
| try | |
| { | |
| var builder = WebApplication.CreateBuilder(args); | |
| builder.Host.UseSerilog((context, services, configuration) => configuration | |
| .ReadFrom.Configuration(context.Configuration) | |
| .ReadFrom.Services(services) | |
| .Enrich.FromLogContext()); | |
| var connectionString = builder.Configuration.GetConnectionString("Postgres") | |
| ?? throw new InvalidOperationException("ConnectionStrings:Postgres não configurada."); | |
| // --- Camadas da aplicação --- | |
| builder.Services.AddApplication(); | |
| builder.Services.AddInfrastructure(builder.Configuration); | |
| builder.Services.AddIntegrations(builder.Configuration); | |
| builder.Services.AddScmMigrations(connectionString); | |
| builder.Services.AddHostedService<SCM.Api.Scheduling.AtividadeCiclicaScheduler>(); | |
| // --- MVC + validação --- | |
| builder.Services | |
| .AddControllers(options => options.Filters.Add<ValidationFilter>()) | |
| .AddJsonOptions(options => | |
| options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())); | |
| // Todo 400 automático (model-binding/validação do framework) usa o mesmo envelope amigável | |
| // { success, message, errors[] } — sem vazar mensagens técnicas (ex.: erro de conversão de GUID/JSON). | |
| builder.Services.Configure<Microsoft.AspNetCore.Mvc.ApiBehaviorOptions>(options => | |
| { | |
| options.InvalidModelStateResponseFactory = context => | |
| { | |
| var campos = context.ModelState | |
| .Where(kv => kv.Value is not null && kv.Value.Errors.Count > 0) | |
| .Select(kv => kv.Key.Replace("$.", string.Empty).Replace("$", string.Empty).Trim()) | |
| .Where(c => !string.IsNullOrEmpty(c)) | |
| .Distinct() | |
| .Select(c => $"Campo '{c}' inválido ou ausente.") | |
| .ToList(); | |
| var payload = SCM.Shared.Api.ApiResponse.Fail( | |
| "Não foi possível processar a requisição: verifique os campos enviados.", | |
| campos.Count > 0 ? campos : null); | |
| return new Microsoft.AspNetCore.Mvc.BadRequestObjectResult(payload); | |
| }; | |
| }); | |
| // --- CORS (SPA Quasar em dev) --- | |
| const string SpaCorsPolicy = "spa"; | |
| var corsOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() | |
| ?? new[] { "http://localhost:9000" }; | |
| builder.Services.AddCors(options => | |
| options.AddPolicy(SpaCorsPolicy, policy => policy | |
| .WithOrigins(corsOrigins) | |
| .AllowAnyHeader() | |
| .AllowAnyMethod())); | |
| // --- Versionamento de API --- | |
| builder.Services | |
| .AddApiVersioning(options => | |
| { | |
| options.DefaultApiVersion = new ApiVersion(1, 0); | |
| options.AssumeDefaultVersionWhenUnspecified = true; | |
| options.ReportApiVersions = true; | |
| }) | |
| .AddApiExplorer(options => | |
| { | |
| options.GroupNameFormat = "'v'VVV"; | |
| options.SubstituteApiVersionInUrl = true; | |
| }); | |
| // --- Autenticação JWT --- | |
| var jwt = builder.Configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>() | |
| ?? throw new InvalidOperationException("Seção 'Jwt' não configurada."); | |
| builder.Services | |
| .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) | |
| .AddJwtBearer(options => | |
| { | |
| options.TokenValidationParameters = new TokenValidationParameters | |
| { | |
| ValidateIssuer = true, | |
| ValidIssuer = jwt.Issuer, | |
| ValidateAudience = true, | |
| ValidAudience = jwt.Audience, | |
| ValidateLifetime = true, | |
| ValidateIssuerSigningKey = true, | |
| IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SecretKey)), | |
| ClockSkew = TimeSpan.FromSeconds(30) | |
| }; | |
| }); | |
| builder.Services.AddAuthorization(); | |
| // --- Swagger / OpenAPI --- | |
| builder.Services.AddEndpointsApiExplorer(); | |
| builder.Services.AddSwaggerGen(options => | |
| { | |
| options.SwaggerDoc("v1", new OpenApiInfo | |
| { | |
| Title = "SCM API", | |
| Version = "v1", | |
| Description = "API REST do SCM 2.0 — gestão para construção civil." | |
| }); | |
| var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; | |
| var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); | |
| if (File.Exists(xmlPath)) | |
| options.IncludeXmlComments(xmlPath, includeControllerXmlComments: true); | |
| var scheme = new OpenApiSecurityScheme | |
| { | |
| Name = "Authorization", | |
| Type = SecuritySchemeType.Http, | |
| Scheme = "bearer", | |
| BearerFormat = "JWT", | |
| In = ParameterLocation.Header, | |
| Description = "Informe: Bearer {seu token JWT}", | |
| Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } | |
| }; | |
| options.AddSecurityDefinition("Bearer", scheme); | |
| options.AddSecurityRequirement(new OpenApiSecurityRequirement { [scheme] = Array.Empty<string>() }); | |
| }); | |
| var app = builder.Build(); | |
| // --- Migrations no startup (controlado por configuração) --- | |
| if (app.Configuration.GetValue("Migrations:RunOnStartup", false)) | |
| { | |
| Log.Information("Aplicando migrations do banco..."); | |
| app.Services.RunScmMigrations(); | |
| } | |
| // --- Pipeline --- | |
| app.UseMiddleware<CorrelationIdMiddleware>(); | |
| app.UseMiddleware<ErrorHandlingMiddleware>(); | |
| app.UseSerilogRequestLogging(); | |
| if (app.Environment.IsDevelopment()) | |
| { | |
| app.UseSwagger(); | |
| app.UseSwaggerUI(); | |
| } | |
| app.UseCors(SpaCorsPolicy); | |
| app.UseAuthentication(); | |
| app.UseAuthorization(); | |
| app.MapControllers(); | |
| app.MapHealthChecks("/health"); | |
| app.Run(); | |
| } | |
| catch (Exception ex) | |
| { | |
| Log.Fatal(ex, "A aplicação falhou ao iniciar."); | |
| } | |
| finally | |
| { | |
| Log.CloseAndFlush(); | |
| } | |
| /// <summary>Exposto como partial para permitir testes de integração com WebApplicationFactory.</summary> | |
| public partial class Program; | |