LaVOZs

The World’s Largest Online Community for Developers

'; c# - asp.net core 3.1 with angular template can no longer respond with 404 and always redirect to spa index.html page - LavOzs.Com

I have an asp.net core 3.1 project with razor pages. I added a spa with angular with <base href="/app" /> so that the app is server under /app. Now, any non existent route returns the spa index.html page instead of 404.

I don't have any client routing on my angular app.

My desired behavior is to respond with 404 if there is no route matching neither razor pages, the api, nor the /app.

However, when i type localhost:5000/non-existent-route, app redirects to my angular index.html app which is not the desired behavior.

Basically, i want to prevent the angular app's index.html from being the fallback default when no route is matched.

Here is my Startup.cs 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.AddRazorPages();
        services.AddControllers().AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; });
        services.AddSwaggerDocument();
        services.AddHealthChecks();
        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; });
        // ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        // app.UseHttpsRedirection();
        app.UseStaticFiles();
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }

        app.UseOpenApi();
        app.UseSwaggerUi3();

        app.UseRouting();

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

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";
            if (env.IsDevelopment())
            {
                spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
            }
        });
    }
}

Not sure if you can do this on the server side, but it is possible on Angular side as below:

@NgModule({
  imports: [
    NgbModule.forRoot(),
    RouterModule.forRoot([
      {
        path: '', component: MainParentComponent, children: [
            { path: '**', component: ErrorComponent } //Default redirection for invalid URLs or unauthorised URLs
        ]
      }
    ])
  ]
})
Related
Unable to find Use.RunTimePageInfo() method in startup.cs file in aspnet core
Specifying default file name for asp.net core static folder
Setting index.html as default page in asp.net core
MVC Razor Pages hosting Angular 4 app
Can't get my Asp.Net Core project to work published to folder on localhost
deploy Angular/Asp.Net Core 2.1 app to AWS: 500 error
How to set default razor page route with asp.net 3.0 middleware