404 pages in ASP.NET MVC

I am building my first ASP.NET MVC website and I am trying to figure out how to implement a 404 page.

Should I create a controller called "404Controller?"? If so, how can I then register this controller with IIS so that it redirects 404s to this page? In addition, in a situation where something is not found (for example, in the database) by any other controller code, how would I redirect the request to my 404 page?

+5
source share
6 answers

My favorite option is to return the view 404.

if (article == null)
    return View("404");

404 404 .

, , .

+7

, , , , - HttpException,

public ActionResult ProductDetails(int id) {

   Product p = this.repository.GetProductById(id);

   if (p == null) {
      throw new HttpException(404, "Not Found");
   }

   return View(p);
}

web.config customError, .

<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
   <error statusCode="404" redirect="Views/Errors/Http404.aspx" />
</customErrors>
+14

MVC 3 HttpNotFoundResult Controller HttpNotFound.

    public ActionResult Index(int id) {
        var myThing = Loader.GetById(id);
        if (myThing == null) {
            return HttpNotFound("Thing Not Found");
        }
        return View(myThing);
    }
+4
  • , NotFoundController , /404, URL- web.config (. @R0MANARMY).

  • throw new HttpException(404, "Not Found") ( ), 404 Response.StatusCode, View("My404Template") .

0

Application_EndRequest MvcApplication MVC 404 Marco Better-Than-Unicorns. " " , new HttpException(404, "Not Found").

0

, - ...

, 404- . ,

@{
    ViewBag.Title = "Page Not Found";
    Response.StatusCode = 404;
}

, -, IIS 404 404.

<system.webServer>
    ...
    <httpErrors errorMode="Detailed" />
</system.webServer>
0

All Articles