SpaDefaultPageMiddleware.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using Microsoft.Extensions.FileProviders;
  2. using Microsoft.Extensions.Options;
  3. namespace WebTemplate.ServerAspects.Spa;
  4. public class SpaDefaultPageMiddleware
  5. {
  6. private readonly RequestDelegate _next;
  7. private readonly IFileProvider _fileProvider;
  8. private readonly IOptions<SpaDefaultPageConfig> _defaultPageOptions;
  9. public SpaDefaultPageMiddleware(
  10. RequestDelegate next,
  11. IOptions<StaticFileOptions> staticFileOptions,
  12. IOptions<SpaDefaultPageConfig> defaultPageOptions,
  13. IWebHostEnvironment hostingEnvironment)
  14. {
  15. _next = next;
  16. _fileProvider = staticFileOptions.Value.FileProvider ?? hostingEnvironment.WebRootFileProvider;
  17. _defaultPageOptions = defaultPageOptions;
  18. }
  19. public async Task InvokeAsync(HttpContext context)
  20. {
  21. // See https://github.com/dotnet/aspnetcore/blob/main/src/Middleware/Spa/SpaServices.Extensions/src/SpaDefaultPageMiddleware.cs
  22. // where this is mostly borrowed from - in combination with the Microsoft.AspNetCore.StaticFiles.DefaultFilesMiddleware code.
  23. if (HttpMethods.IsGet(context.Request.Method) && context.GetEndpoint() == null)
  24. {
  25. // StaticFileMiddleware comes _after_ this middleware, so we use the file provider that is used by
  26. // the static file middleware to figure out ahead of time if there is actually a file matching the
  27. // request path and if not, we just "re-target" the request to our default page.
  28. var fileInfo = _fileProvider.GetFileInfo(context.Request.Path);
  29. if (!fileInfo.Exists)
  30. {
  31. context.Request.Path = _defaultPageOptions.Value.DefaultPage;
  32. }
  33. }
  34. await _next(context);
  35. }
  36. }