ASP.net core MVC catch all route serve static file

前端 未结 7 2233
悲&欢浪女
悲&欢浪女 2020-12-13 09:20

Is there a way to make a catch all route serve a static file?

Looking at this http://blog.nbellocam.me/2016/03/21/routing-angular-2-asp-net-core/

I basically

相关标签:
7条回答
  • 2020-12-13 09:54

    In order to serve index.html from wwwroot folder the following directives should be added (.Net Core 2).

    This allows to serve static files:

    app.UseStaticFiles();
    

    This allows to get default files, e.g. index.html:

    app.UseDefaultFiles();
    
    0 讨论(0)
  • 2020-12-13 10:04

    In ASP.NET Core 3.1, I've used the following:

    Startup.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();
    
        app.UseCors();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    
        app.UseDefaultFiles();
        app.UseStaticFiles();
    }
    

    MyController.cs

    [HttpGet("{anything}")]
    public IActionResult GetSPA()
    {
        return File("~/index.html", "text/html");
    }
    
    0 讨论(0)
  • In case you don't want manually specify which routes are for api:

    app.UseDefaultFiles();
    app.UseStaticFiles();
    
    app.UseMvc() // suggestion: you can move all the SPA requests to for example /app/<endpoints_for_the_Spa> and let the mvc return 404 in case <endpoints_for_the_Spa> is not recognized by the backend. This way SPA will not receive index.html
    
    // at this point the request did not hit the api nor any of the files
    
    // return index instead of 404 and let the SPA to take care of displaying the "not found" message
    app.Use(async (context, next) => {
        context.Request.Path = "/index.html";
        await next();
    });
    app.UseStaticFiles(); // this will return index.html
    
    0 讨论(0)
  • 2020-12-13 10:09

    ASP.NET Core catch all routes for Web API and MVC are configured differently

    With Web API (if you're using prefix "api" for all server-side controllers eg. Route("api/[controller"]):

    app.Use(async (context, next) => 
    { 
        await next(); 
        var path = context.Request.Path.Value;
    
        if (!path.StartsWith("/api") && !Path.HasExtension(path)) 
        { 
            context.Request.Path = "/index.html"; 
            await next(); 
        } 
    });            
    
    app.UseStaticFiles();
    app.UseDefaultFiles();
    
    app.UseMvc();
    

    With MVC (dotnet add package Microsoft.AspNetCore.SpaServices -Version x.y.z):

    app.UseStaticFiles();
    app.UseDefaultFiles();
    
    app.UseMvc(routes => 
    { 
        routes.MapRoute( 
            name: "default", 
            template: "{controller=Home}/{action=Index}"); 
    
        routes.MapSpaFallbackRoute("spa", new { controller = "Home", action = "Index" }); 
    });  
    
    0 讨论(0)
  • 2020-12-13 10:14

    If you're already in the routing stage, you've gone past the point where static files are served in the pipeline. Your startup will look something like this:

    app.UseStaticFiles();
    
    ...
    
    app.UseMvc(...);
    

    The order here is important. So your app will look for static files first, which makes sense from a performance standpoint - no need to run through MVC pipeline if you just want to throw out a static file.

    You can create a catch-all controller action that will return the content of the file instead. For example (stealing the code in your comment):

    public IActionResult Spa()
    {
        return File("~/index.html", "text/html");
    }
    
    0 讨论(0)
  • 2020-12-13 10:16

    I had to make some additions to @DavidG answer. Here is what I ended up with

    Startup.cs

    app.UseStaticFiles();
    
    app.UseMvc(routes =>
    {
       routes.MapRoute("default", "{controller}/{action}");
    
       routes.MapRoute("Spa", "{*url}", defaults: new { controller = "Home", action = "Spa" });
    });
    

    HomeController.cs

    public class HomeController : Controller
    {
      public IActionResult Spa()
      {
          return File("~/index.html", "text/html");
      }
    }
    
    0 讨论(0)
提交回复
热议问题