| | | 1 | | using Microsoft.AspNetCore.StaticFiles; |
| | | 2 | | using Microsoft.Net.Http.Headers; |
| | | 3 | | |
| | | 4 | | namespace Anichron.API.Infrastructure; |
| | | 5 | | |
| | | 6 | | public static class UiServing |
| | | 7 | | { |
| | | 8 | | private const string hashedAssets = "/assets"; |
| | | 9 | | private const string index = "/index.html"; |
| | | 10 | | |
| | | 11 | | extension(WebApplication app) |
| | | 12 | | { |
| | | 13 | | public WebApplication UseUi() |
| | 33 | 14 | | { |
| | 33 | 15 | | app.Use((context, next) => |
| | 33 | 16 | | { |
| | 33 | 17 | | if (context.GetEndpoint() is not null) |
| | 33 | 18 | | return next(context); |
| | 33 | 19 | | if (ApiPaths.IsApi(context.Request.Path)) |
| | 33 | 20 | | return Results.Problem(statusCode: StatusCodes.Status404NotFound).ExecuteAsync(context); |
| | 33 | 21 | | if (IsAppRoute(context.Request)) |
| | 33 | 22 | | context.Request.Path = index; |
| | 33 | 23 | | return next(context); |
| | 33 | 24 | | }); |
| | 33 | 25 | | app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = SetCacheControl }); |
| | 33 | 26 | | return app; |
| | | 27 | | } |
| | | 28 | | } |
| | | 29 | | |
| | | 30 | | private static bool IsAppRoute(HttpRequest request) |
| | 21 | 31 | | => (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method)) |
| | 21 | 32 | | && !Path.HasExtension(request.Path.Value); |
| | | 33 | | |
| | | 34 | | private static void SetCacheControl(StaticFileResponseContext context) |
| | 14 | 35 | | { |
| | 14 | 36 | | context.Context.Response.Headers[HeaderNames.CacheControl] = |
| | 14 | 37 | | context.Context.Request.Path.StartsWithSegments(hashedAssets) |
| | 14 | 38 | | ? "public, max-age=31536000, immutable" |
| | 14 | 39 | | : "no-cache"; |
| | 14 | 40 | | } |
| | | 41 | | } |