Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
164 lines (130 loc) · 4.44 KB
/
Copy pathProgram.cs
File metadata and controls
164 lines (130 loc) · 4.44 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
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
161
162
163
164
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Security.Claims;
using BasicApiEndpoints.Service;
using BasicApiEndpoints.Endpoints;
using BasicApiEndpoints.Middleware;
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Configure Serilog as the application's logging provider.
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.CreateLogger();
builder.Host.UseSerilog();
builder.Services.AddHttpLogging(logging =>
{
logging.LoggingFields =
HttpLoggingFields.RequestMethod |
HttpLoggingFields.RequestPath |
HttpLoggingFields.ResponseStatusCode;
logging.CombineLogs = true;
});
// Register application services and MVC controller support.
builder.Services.AddSingleton<IBlogService, BlogService>();
builder.Services.AddSingleton<ProductService>();
builder.Services.AddControllers();
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole("Administrator");
});
});
var app = builder.Build();
app.UseMiddleware<RequestTimingMiddleware>();
app.UseHttpLogging();
// Global exception handling middleware
// Catch unhandled exceptions from requests and return a generic 500 response.
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
app.Logger.LogError(
ex,
"Unhandled exception occurred while processing {Method} {Path}",
context.Request.Method,
context.Request.Path);
if (context.Response.HasStarted)
{
throw;
}
context.Response.Clear();
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(new
{
message = "Something went wrong."
});
}
});
app.UseMiddleware<PipelineDemoMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
// Map attribute-routed controllers and serialization endpoints.
app.MapControllers();
app.MapSerializationEndpoints();
app.MapDeserializationEndpoints();
app.MapSerializationSecurityEndpoints();
// Minimal API route examples.
app.MapGet("/", () => "Root Path");
app.MapGet("/downloads", () => "Downloads");
app.MapGet("/users/{userID}/posts/{slug}", (int userID, string slug) => {
return $"User ID: {userID}, Post ID: {slug}";
});
app.MapGet("/products/{id:int:min(0)}", (int id) => {
return $"Product ID: {id}";
});
app.MapGet("/report/{year?}" , (int? year = 2026) => {
return $"Report for year: {year}";
});
app.MapGet("/files/{*filepath}", (string filePath) => {
return $"File Path: {filePath}";
});
app.MapGet("/search", (string? q, int? page = 1) => {
if (string.IsNullOrEmpty(q))
{
return "No search query provided.";
}
return $"Search results for: {q}, Page: {page}";
});
app.MapGet("/store/{category}/{productID:int?}/{*extraPath}", (string category, int? productID, string? extraPath, bool inStock = true) => {
return $"Category: {category}, Product ID: {productID}, Extra Path: {extraPath}, In Stock: {inStock}";
});
app.MapPut("/" , () => "This is a PUT request to the root path");
app.MapDelete("/", () => "Delete request to the root path");
app.MapPost("/", () => "POST request to the root path");
app.MapGet("/middleware/pass", (ILogger<Program> logger) =>
{
logger.LogInformation("Endpoint: handling the request");
return Results.Ok(new
{
message = "Request reached the endpoint."
});
});
app.MapGet("/middleware/blocked", (ILogger<Program> logger) =>
{
logger.LogInformation(
"Endpoint: this should never run");
return Results.Ok(new
{
message = "You should never receive this response."
});
});
// Add the protection policy to the /security/admin endpoint, requiring the user to be authenticated and have the "Administrator" role.
app.MapGet("/security/admin", (ClaimsPrincipal user) =>
{
return Results.Ok(new
{
message = "Administrator access granted.",
name = user.Identity?.Name
});
})
.RequireAuthorization("AdminOnly");
app.Run();