0
public class BookController : Controller
{
   public ActionResult Show(int bid)
   {
    return View();
   }
}
routes.MapRoute(
                name: "Show",
                url: "Book/{bid}/",
                defaults: new {controller = "Book", action = "Show"},
                constraints: new {bid = @"\d+"}
                );

if visit

/book/test/

it will return 500 error, how to return 404 error?

if router don't match,how to return 404?

Jack
  • 1

1 Answers1

0

You could get an actual view to be displayed instead by adding a customErrors element to your web.config that will redirect the user to a specific url when a certain status code occurs which you can then handle as you would with any url. Here's a walk-through below:

First throw the HttpException where applicable. When instantiating the exception, be sure to use one of the overloads which takes a http status code as a parameter like below.

throw new HttpException(404, "NotFound");

Then add an custom error handler in your web.config file so that you could determine what view should be rendered when the above exception occurs. Here's an example below:

<configuration>
    <system.web>
        <customErrors mode="On">
          <error statusCode="404" redirect="~/404"/>
        </customErrors>
    </system.web>
</configuration>

Now add a route entry in your Global.asax that'll handle the url "404" which will pass the request to a controller's action that'll display the View for your 404 page.

Global.asax

routes.MapRoute(
    "404", 
    "404", 
    new { controller = "Commons", action = "HttpStatus404" }
);

CommonsController

public ActionResult HttpStatus404()
{
    return View();
}

All that's left is to add a view for the above action.

Dharti Sojitra
  • 207
  • 1
  • 10