-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
75 lines (60 loc) · 1.74 KB
/
Program.cs
File metadata and controls
75 lines (60 loc) · 1.74 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
72
73
74
75
using Microsoft.Extensions.FileProviders;
using Microsoft.EntityFrameworkCore;
using TodoApi.Data;
var builder = WebApplication.CreateBuilder(args);
// Register services
builder.Services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Enable CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
// Middleware
app.UseHttpsRedirection();
// Serve `/docs` folder
var docsPath = Path.Combine(Directory.GetCurrentDirectory(), "docs");
if (Directory.Exists(docsPath))
{
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(docsPath),
RequestPath = "/docs"
});
}
// Enable CORS
app.UseCors("AllowAll");
// Swagger
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "TodoApi v1");
options.RoutePrefix = "api-docs";
});
// Authorization
app.UseAuthorization();
app.MapControllers();
// Custom landing page at "/"
app.MapGet("/", (HttpContext context) =>
{
var swaggerUrl = $"{context.Request.Scheme}://{context.Request.Host}/api-docs";
var docsUrl = $"{context.Request.Scheme}://{context.Request.Host}/docs/index.html";
return Results.Text(
$"""
<h1>TodoAPI</h1>
<p>See the <a href='{swaggerUrl}'>Swagger UI</a>.</p>
<p>Test the <a href='{docsUrl}'>Frontend</a>.</p>
""",
"text/html"
);
});
app.Run("http://0.0.0.0:" + (Environment.GetEnvironmentVariable("PORT") ?? "5065"));