Search code examples
.net-coresingle-page-applicationhttpsys

How to configure dotnet core 3 to serve up React SPA while using Http.sys and a URLPrefix?


After changing the URLPrefix I get the following error:

The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.

Something thus is required to tell dotnet core about the prefix but I can't seem to find the right combination of settings.

Help much appreciated.

The code is below:

HostBuilder is setup with:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseHttpSys(options =>
        {
            options.AllowSynchronousIO = false;
            options.Authentication.Schemes = AuthenticationSchemes.None;
            options.Authentication.AllowAnonymous = true;
            options.MaxConnections = null;
            options.MaxRequestBodySize = 30000000;
            options.UrlPrefixes.Add("http://localhost:5005/Product/Site");
        });
        webBuilder.UseStartup<Startup>();
    });

ConfigureServices:

public override void ConfigureServices(IServiceCollection services)
{
  services.AddRazorPages();

  services.AddSpaStaticFiles(configuration =>
  {
    configuration.RootPath = "ClientApp/build";
  });

  services.AddMvc();
  services.AddResponseCompression(opts =>
  {
    opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
              new[] { "application/octet-stream" });
  });
}

And then Configure is:

      app.UseSpaStaticFiles();
      app.UseRouting();
      app.UseEndpoints
      (
        endpoints =>
        {
          endpoints.MapControllerRoute(
              name: "default",
              pattern: "{controller}/{action=Index}/{id?}");
        }
      );

      app.UseSpa(spa =>
      {
        //spa.Options.DefaultPage = reactPath + "/index.html";
        spa.Options.DefaultPage = "/index.html";

        spa.Options.SourcePath = "ClientApp";


      });

Solution

  • This appears to be an issue where the path to the actual static files is lost. In your StaticFilesOptions ensure that you are providing a File provider with the path to your index.html static files.

    spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
                {
                  FileProvider = new PhysicalFileProvider
                  (
                    @"<YourPath>"
                  )
                }
    

    Further details for these options can be found in Microsoft's documentation.

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1