Currently, while working on my application with Angular 4.1.1
, I have a habit of declaring routing in every module I create.
For instance, in the file new-cars.routing.module.ts
:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NewCarsComponent} from './new-cars.component';
import { NewCarsResolver } from './new-cars.resolver';
@NgModule({
imports: [
RouterModule.forChild([
{
path: 'cars/:id',
component: NewCarsComponent,
resolve: {
card: NewCarsResolver
}
}
])
],
exports: [RouterModule]
})
export class NewCarsRoutingModule { }
I also define routes in the app-routing.module.ts
to handle incorrect routes:
export const routes: Routes = [
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true})],
exports: [RouterModule]
})
export class AppRoutingModule {}
To properly manage misconfigured URLs, I ensure that addresses are formatted as follows:
http://foowebsite/#/sdf /*this address exists*/
However, if the URL is incorrectly inputted like below:
http://foowebsite/#/news/-5 /*There is no route param "-5". It should show a 404 error page instead of redirecting to home*/
http://foowebsite/sdf /*This routing does not exist. Instead of redirecting to home, display a 404 error */
Various attempts were made such as:
export const routes: Routes = [
{ path: '404', component: PageNotFoundComponent },
{ path: '**', component: PageNotFoundComponent }
];
along with:
export const routes: Routes = [
{ path: '404', component: PageNotFoundComponent },
{ path: '**', redirectTo: '/404' }
];
Unfortunately, these configurations still redirect invalid URLs to the home page. Keep in mind that module routing handles module-specific routes and application routing directs to a 404 page.
In my app.module.ts
file:
import { AppRoutingModule } from './app-routing.module';
@NgModule({
imports: [
...
AppRoutingModule
],
declarations: [
AppComponent,
PageNotFoundComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
In the ASP.NET Core Web Application web.config
file, the setup is as follows:
<system.webServer>
<httpErrors>
<remove statusCode="500" subStatusCode="-1" />
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="" path="/404"
responseMode="ExecuteURL" />
<error statusCode="500" prefixLanguageFilePath="" path="/404"
responseMode="ExecuteURL" />
<error statusCode="500" subStatusCode="100" path="/404"
responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
Even deliberately returning a 404
error code doesn't trigger the error page:
[HttpGet("{name}")]
public async Task<IActionResult> Get(string name)
{
return StatusCode(404);
}
Can someone provide guidance on how to correctly redirect to the 404 page?