There are two possible scenarios: one is that the default route cannot match, and the other is that the default route match is incorrect.
Prerequisites:
Create an errorcontroller
Public class errorcontroller: Controller
{
Public actionresult http404 ()
{
Return view ();
}
}
Add http404.aspx
For the first scenario:
1. Create a mycontrollerfactory class under Models
Public class mycontrollerfactory: defaultcontrollerfactory
{
Protected override icontroller getcontrollerinstance (system. Web. Routing. requestcontext, type controllertype)
{
Try
{
Return base. getcontrollerinstance (requestcontext, controllertype );
}
Catch (httpexception ex)
{
Int httpcode = ex. gethttpcode ();
If (httpcode = (INT) httpstatuscode. notfound)
{
Icontroller controller = new errorcontroller ();
(Errorcontroller) controller). http404 ();
Return controller;
}
Else
{
Throw ex;
}
}
}
}
2. In the application_start method of the global. asax file, add
Controllerbuilder. Current. setcontrollerfactory (New mycontrollerfactory ());
Then http: // localhost: 1124/randomcontroller/randomaction/randomid will specify its own error page, but http: // localhost: 1124/Homer/randomaction/randomid won't.
The second scenario is required:
1. Create a basecontroller
Public class basecontroller: Controller
{
Protected override void handleunknownaction (string actionname)
{
Routeto404 (httpcontext );
}
Public actionresult routeto404 (httpcontextbase context)
{
Icontroller errorcontroller = new errorcontroller ();
Routedata RD = new routedata ();
Rd. Values. Add ("controller", "error ");
Rd. Values. Add ("action", "http404 ");
Errorcontroller. Execute (New requestcontext (context, RD ));
Return new emptyresult ();
}
}
2. Change the existing controller from the inherited controller to the basecontroller.
So OK.