Asp.net MVC learning diary 4 (if you cannot route, point to the custom error page)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.