-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathProgram.cs
More file actions
71 lines (58 loc) · 2.17 KB
/
Program.cs
File metadata and controls
71 lines (58 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System.Net;
using System.Text.Json;
using CustomJwt.Exceptions;
using CustomJwt.Middlewares;
using CustomJwt.Repositories;
using Microsoft.AspNetCore.Diagnostics;
var builder = WebApplication.CreateBuilder(args);
// extensions method untuk me-register sql server data context ke dalam IoC container
builder.Services.AddSqlServer<DataContext>(builder.Configuration.GetConnectionString("DataContext"));
// add default cors policy
builder.Services.AddCors(options => options
.AddDefaultPolicy(cors =>
cors.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
// ensure database is created
var serviceScope = app.Services.GetService<IServiceScopeFactory>()?.CreateScope();
var db = serviceScope?.ServiceProvider.GetRequiredService<DataContext>();
db?.Database.EnsureCreated();
DataInitializer.Run(db);
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors();
// global error handler
app.UseExceptionHandler(appBuilder =>
{
appBuilder.Run(async context =>
{
var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
if (contextFeature == null) return;
context.Response.StatusCode = contextFeature.Error switch
{
OperationCanceledException => (int)HttpStatusCode.ServiceUnavailable,
BadRequestException => (int)HttpStatusCode.BadRequest,
NotFoundException => (int)HttpStatusCode.NotFound,
ForbiddenException => (int)HttpStatusCode.Forbidden,
UnauthorizedException => (int)HttpStatusCode.Unauthorized,
_ => (int)HttpStatusCode.InternalServerError
};
var errorResponse = new
{
statusCode = context.Response.StatusCode,
message = contextFeature.Error.GetBaseException().Message
};
await context.Response.WriteAsync(JsonSerializer.Serialize(errorResponse));
});
});
app.UseMiddleware<JwtMiddleware>();
app.MapControllers();
app.Run();