简体   繁体   中英

Serving angular with routes in asp.net core 2 project

I have an angular project that I build with the cli "ng build --prod" and put in the wwwroot directory of my asp.net core project which I want to serve the site with. The asp project has no MVC controllers I'm using so I don't have to take that into consideration.

I Setup the application to use default files and static files. That gives me the angular application when I navigate to the server root, in this case, localhost:5000 => (delivers) index.html. From there I can use the application and routes work.

But when I try to link to any route manually (eg. typing http://localhost:5000/quality-test-list ) I only get a white page with nothing.

My guess is that the server side routing is prohibiting this. I have looked at the standard "dotnet new angular" project files but I cannot figure it out.

My startup file:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseDefaultFiles();
        app.UseStaticFiles();

    }
}

in your configure section, use the app.use method to configure all 404 to your index.html

    app.Use(async (context, next) => {
              await next();
              if(context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)){
                  context.Request.Path = "/index.html";
                  await next();
              }
    })
    .UseDefaultFiles(new DefaultFilesOptions { DefaultFilesName = new List<string>{ "index.html" } })
    .UseStaticFiles(new StaticFilesOptions 
                    {
                       FileProvider = new PhysicalFileProvider(
                           Path.Combine(Directory.GetCurrentDiretory(), "@wwwroot")),
                           RequestPath = new PathString("")
    })
    .UseMvc();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM