-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
160 lines (136 loc) · 5.97 KB
/
Program.cs
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using System.Reflection;
using Serilog;
using Microsoft.EntityFrameworkCore;
using GrpcCrudBoilerplate.Services.Authentication;
using GrpcCrudBoilerplate.GrpcServices.v1;
using GrpcCrudBoilerplate.Mappings;
using GrpcCrudBoilerplate.Services.Order;
using GrpcCrudBoilerplate.Infrastructure.Authorization;
using GrpcCrudBoilerplate.Services.Authorization;
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
//.WriteTo.File("logs/GrpcCrudBoilerplate-.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.With<CorrelationIdEnricher>()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
.WriteTo.File("logs/GrpcCrudBoilerplate-.txt", rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {CorrelationId} {Message:lj}{NewLine}{Exception}")
.CreateLogger();
try
{
Log.Information("Starting web application");
var builder = WebApplication.CreateBuilder(args);
// Add Serilog
builder.Host.UseSerilog();
// Configure Kestrel to use both HTTP/1.1 and HTTP/2
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenLocalhost(5000, o => o.Protocols = HttpProtocols.Http1AndHttp2);
options.ListenLocalhost(5001, o =>
{
o.Protocols = HttpProtocols.Http2;
o.UseHttps();
});
});
// Add services to the container.
builder.Services.AddGrpcReflection();
builder.Services.AddSingleton<IJwtTokenService, JwtTokenService>();
// Add DbContext
builder.Services.AddDbContext<GrpcCrudBoilerplate.DataContext.AppDbContext>(options =>
options.UseInMemoryDatabase("TestDb")); // In-memory database
// Add exception interceptor
builder.Services.AddGrpc(options =>
{
options.Interceptors.Add<GrpcCrudBoilerplate.Infrastructure.ExceptionHandling.ExceptionInterceptor>();
options.Interceptors.Add<RequirePermissionInterceptor>();
});
builder.Services.AddAutoMapper(typeof(MappingProfile));
builder.Services.AddMemoryCache();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key is not configured")))
};
});
builder.Services.AddAuthorization();
builder.Services.AddGrpc().AddJsonTranscoding();
builder.Services.AddGrpcSwagger();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Grpc Crud Example", Version = "v1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.IncludeGrpcXmlComments(xmlPath, includeControllerXmlComments: true);
c.AddServer(new OpenApiServer { Url = "http://localhost:5000", Description = "HTTP/1.1 and HTTP/2" });
c.AddServer(new OpenApiServer { Url = "https://localhost:5001", Description = "HTTPS (HTTP/2)" });
c.DocumentFilter<GrpcCrudBoilerplate.GrpcDocumentFilter>();
});
// Add Services
builder.Services.AddScoped<IOrderService, GrpcCrudBoilerplate.Services.Order.OrderService>();
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
builder.Services.AddScoped<IAuthorizationService, AuthorizationService>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<IUserContext, UserContext>();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseCorrelationId();
app.UseAuthentication();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Grpc Crud Example V1");
//c.RoutePrefix = string.Empty;
c.EnableTryItOutByDefault();
});
// Map gRPC service
app.MapGrpcService<GreeterService>();
app.MapGrpcService<OrderImportService>();
app.MapGrpcService<GrpcCrudBoilerplate.GrpcServices.v1.OrderService>();
app.MapGrpcService<AuthService>();
app.MapGrpcReflectionService();
// Add this line to serve the Swagger UI at the root
app.MapGet("/", () => Results.Redirect("/swagger"));
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/swagger"))
{
context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
context.Response.Headers.Append("Pragma", "no-cache");
context.Response.Headers.Append("Expires", "0");
}
await next();
});
// Seed initial data
using (var scope = app.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<GrpcCrudBoilerplate.DataContext.AppDbContext>();
GrpcCrudBoilerplate.DataContext.SeedInitialData.Initialize(context);
}
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}