What is the difference between UseStaticFiles, UseSpaStaticFiles, and UseSpa in ASP.NET Core 2.1?

前端 未结 2 1882
我在风中等你
我在风中等你 2020-12-13 08:50

ASP.NET Core 2.1.1 offers several seemingly related extension methods for appBuilder:

  • UseStaticFiles from Microsoft.AspNetCore.StaticFiles
2条回答
  •  眼角桃花
    2020-12-13 09:07

    1. UseStaticFiles serves files from wwwroot but it can be changed.
    2. UseSpaStaticFiles does a similar thing but it requires ISpaStaticFileProvider to be registered. If app.ApplicationServices.GetService() returns null, then you will get an exception.
    throw new InvalidOperationException($"To use {nameof(UseSpaStaticFiles)}, you must " +
                        $"first register an {nameof(ISpaStaticFileProvider)} in the service provider, typically " +
                        $"by calling services.{nameof(AddSpaStaticFiles)}.");
    

    So you need to call app.AddSpaStaticFiles() to register default ISpaStaticFileProvider

    1. UseSpa does two things. Rewrites all requests to the default page and tries to configure static files serving. On the contrary to UseSpaStaticFiles it does not throw an exception but just falls back to wwwroot folder.

    Actually UseSpaStaticFiles and UseSpa both internally call the same method UseSpaStaticFilesInternal but with a different value for the 3rd parameter which is allowFallbackOnServingWebRootFiles. That is the reason why UseSpaStaticFiles throws an exception if no ISpaStaticFileProvider was registered it simply does not allow to fall back to wwwroot.

    BTW if UseSpa falls back to wwwroot internally it calls old good app.UseStaticFiles(staticFileOptions);

    Links to github sources: 1. SpaDefaultMiddleware 2. SpaStaticFilesExtensions

提交回复
热议问题