SlideShare a Scribd company logo
1 of 4
Download to read offline
W E D N E S D A Y , A P R I L 1 0 , 2 0 1 3
Handling 404 Error in ASP.NET MVC
In ASP.NET Web Forms, handling 404 errors are easy - which is basically a web.config setting. In
ASP.NET MVC, it is a bit more complicated. Why is it more complicated? In comparison, everything
is seemingly easier in MVC than WebForm.
It is more complicated mainly because of Routing. In WebForm, most 404 occurs because of non-
existent file and each UR: is usually mapped to a particular file (aspx). With MVC, that is not the
case. All requests are handled by the Routing table and based on that it will invoke appropriate
controller and actions etc. Secondly, our basic default route usually is quite common
({controller}/{action}/{id}) - therefore most URL request will be caught by this route.
So, let's dive in on how can we do proper handling of 404 errors with ASP.NET MVC.
TURN ON CUSTOM ERROR IN WEB.CONFIG
1. <customErrors mode="On" defaultRedirect="~/Error/Error">
2. <error statusCode="404" redirect="~/Error/Http404" />
3. </customErrors>
DECLARE DETAIL ROUTES MAPPED IN ROUTE TABLE
So instead of just using the default route:
1. routes.MapRoute(
2. name: "Default",
3. url: "{controller}/{action}/{id}",
4. defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
5. );
Declare all your intended route explicitly and create a "catch-all" to handle non-matching route -
which basically a 404. In MVC, a 404 can happen when you try to access a URL where the there is
no controller for. This code in the routing table handles that scenario.
1. routes.MapRoute(
2. name: "Account",
3. url: "Account/{action}/{id}",
4. defaults: new { controller = "Account", action = "Index", id =
UrlParameter.Optional }
5. );
6.
7. routes.MapRoute(
8. name: "Home",
9. url: "Home/{action}/{id}",
10. defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
11. );
12.
13. routes.MapRoute(
14. name: "Admin",
15. url: "Admin/{action}/{id}",
16. defaults: new { controller = "Admin", action = "Index", id =
UrlParameter.Optional }
17. );
18.
19. routes.MapRoute(
20. name: "404-PageNotFound",
21. url: "{*url}",
22. defaults: new { controller = "Home", action = "Http404" }
23. );
OVERRIDE HANDLEUNKNOWNACTION IN BASECONTROLLER CLASS
Create a Controller base class that every controller in your application inherits from. In that base
controller class, override HandleUnknownAction method. Now, another scenario that a 404 may
happen is that when the controller exists, but there is no action for it. In this case, the routing
table will not be able to trap it easily - but the controller class has a method that handle that.
1. [AllowAnonymous]
2. public class ErrorController : Controller
3. {
4. protected override void HandleUnknownAction(string actionName)
5. {
6. if (this.GetType() != typeof(ErrorController))
7. {
8. var errorRoute = new RouteData();
9. errorRoute.Values.Add("controller", "Error");
10. errorRoute.Values.Add("action", "Http404");
11. errorRoute.Values.Add("url",
HttpContext.Request.Url.OriginalString);
12.
13. View("Http404").ExecuteResult(this.ControllerContext);
14. }
15. }
16.
17. public ActionResult Http404()
18. {
19. return View();
20. }
21.
22. public ActionResult Error()
23. {
24. return View();
25. }
26. }
CREATE CORRESPONDING VIEWS
View for generic error: Error.chtml
1. @model System.Web.Mvc.HandleErrorInfo
2.
3. @{
4. ViewBag.Title = "Error";
5. }
6.
7. <hgroup class="title">
8. <h1 class="error">Error.</h1>
9. <br />
10. <h2 class="error">An error occurred while processing your request.</h2>
11. @if (Request.IsLocal)
12. {
13. <p>
14. @Model.Exception.StackTrace
15. </p>
16. }
17. else
18. {
19. <h3>@Model.Exception.Message</h3>
20. }
21. </hgroup>
View for 404 error: Http404.chtml
1. @model System.Web.Mvc.HandleErrorInfo
2.
3. @{
4. ViewBag.Title = "404 Error: Page Not Found";
5. }
6. <hgroup class="title">
7. <h1 class="error">We Couldn't Find Your Page! (404 Error)</h1><br />
8. <h2 class="error">Unfortunately, the page you've requested cannot be
displayed. </h2><br />
9. <h2>It appears that you've lost your way either through an outdated link <br
/>or a typo on the page you were trying to reach.</h2>
10. </hgroup>

More Related Content

What's hot

Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule Rajkattamuri
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in muleRajkattamuri
 
Quartz component in mule
Quartz component in muleQuartz component in mule
Quartz component in mulejaveed_mhd
 
1時間で作るマッシュアップサービス(関西版)
1時間で作るマッシュアップサービス(関西版)1時間で作るマッシュアップサービス(関西版)
1時間で作るマッシュアップサービス(関西版)Yuichiro MASUI
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
multiple views and routing
multiple views and routingmultiple views and routing
multiple views and routingBrajesh Yadav
 
OWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinOWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinTobias Zander
 
OWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP ProgrammersOWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP Programmersrjsmelo
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asppriya Nithya
 
Using Angular with Rails
Using Angular with RailsUsing Angular with Rails
Using Angular with RailsJamie Davidson
 
SQL Injection in PHP
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHPDave Ross
 

What's hot (18)

Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
 
Quartz component in mule
Quartz component in muleQuartz component in mule
Quartz component in mule
 
1時間で作るマッシュアップサービス(関西版)
1時間で作るマッシュアップサービス(関西版)1時間で作るマッシュアップサービス(関西版)
1時間で作るマッシュアップサービス(関西版)
 
Life cycle of web page
Life cycle of web pageLife cycle of web page
Life cycle of web page
 
Softlayer_API_openWhisk
Softlayer_API_openWhiskSoftlayer_API_openWhisk
Softlayer_API_openWhisk
 
Routes
RoutesRoutes
Routes
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Devise and Rails
Devise and RailsDevise and Rails
Devise and Rails
 
Two database findings
Two database findingsTwo database findings
Two database findings
 
multiple views and routing
multiple views and routingmultiple views and routing
multiple views and routing
 
Demanding scripting
Demanding scriptingDemanding scripting
Demanding scripting
 
Pundit
PunditPundit
Pundit
 
OWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in BerlinOWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in Berlin
 
OWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP ProgrammersOWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP Programmers
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
 
Using Angular with Rails
Using Angular with RailsUsing Angular with Rails
Using Angular with Rails
 
SQL Injection in PHP
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHP
 

Viewers also liked

pengalaman Sertifikat
pengalaman Sertifikatpengalaman Sertifikat
pengalaman Sertifikatdefit chan
 
Cement Australia - Energy Efficiency Opportunities Public Report 2010
Cement Australia - Energy Efficiency Opportunities Public Report 2010Cement Australia - Energy Efficiency Opportunities Public Report 2010
Cement Australia - Energy Efficiency Opportunities Public Report 2010hong8reason
 
инструкция по созданию кроссвордов
инструкция по созданию кроссвордовинструкция по созданию кроссвордов
инструкция по созданию кроссвордовirina1112
 
Jd aunipark-commercial-projects-presentation
Jd aunipark-commercial-projects-presentationJd aunipark-commercial-projects-presentation
Jd aunipark-commercial-projects-presentationJD GROUP
 
Инструкция по работе с интернет сервисом "Фабрика кроссвордов"
Инструкция по работе с интернет сервисом "Фабрика кроссвордов"Инструкция по работе с интернет сервисом "Фабрика кроссвордов"
Инструкция по работе с интернет сервисом "Фабрика кроссвордов"irina1112
 
5.05 Analyzing 20th Century Poetry
5.05 Analyzing 20th Century Poetry5.05 Analyzing 20th Century Poetry
5.05 Analyzing 20th Century PoetryJoanna Roberts
 
Class Research Project Final
Class Research Project FinalClass Research Project Final
Class Research Project FinalAlexandra Collins
 
marche international
marche internationalmarche international
marche internationalsalahovech
 

Viewers also liked (13)

pengalaman Sertifikat
pengalaman Sertifikatpengalaman Sertifikat
pengalaman Sertifikat
 
Cement Australia - Energy Efficiency Opportunities Public Report 2010
Cement Australia - Energy Efficiency Opportunities Public Report 2010Cement Australia - Energy Efficiency Opportunities Public Report 2010
Cement Australia - Energy Efficiency Opportunities Public Report 2010
 
инструкция по созданию кроссвордов
инструкция по созданию кроссвордовинструкция по созданию кроссвордов
инструкция по созданию кроссвордов
 
Jd aunipark-commercial-projects-presentation
Jd aunipark-commercial-projects-presentationJd aunipark-commercial-projects-presentation
Jd aunipark-commercial-projects-presentation
 
07 02-05
07 02-0507 02-05
07 02-05
 
07 02-05
07 02-0507 02-05
07 02-05
 
07 02-05
07 02-0507 02-05
07 02-05
 
Инструкция по работе с интернет сервисом "Фабрика кроссвордов"
Инструкция по работе с интернет сервисом "Фабрика кроссвордов"Инструкция по работе с интернет сервисом "Фабрика кроссвордов"
Инструкция по работе с интернет сервисом "Фабрика кроссвордов"
 
5.05
5.055.05
5.05
 
SRAP3001 - Research Project
SRAP3001 - Research ProjectSRAP3001 - Research Project
SRAP3001 - Research Project
 
5.05 Analyzing 20th Century Poetry
5.05 Analyzing 20th Century Poetry5.05 Analyzing 20th Century Poetry
5.05 Analyzing 20th Century Poetry
 
Class Research Project Final
Class Research Project FinalClass Research Project Final
Class Research Project Final
 
marche international
marche internationalmarche international
marche international
 

Similar to 07-02-05

ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsLukasz Lysik
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvcmicham
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
Http programming in play
Http programming in playHttp programming in play
Http programming in playKnoldus Inc.
 
Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Maarten Balliauw
 
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsCustom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsAkhil Mittal
 
Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Visug
 
Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Maarten Balliauw
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVCGuy Nir
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravelConfiz
 
Web service with Laravel
Web service with LaravelWeb service with Laravel
Web service with LaravelAbuzer Firdousi
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0Korhan Bircan
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Claire Townend Gee
 

Similar to 07-02-05 (20)

ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
 
Asp Net Architecture
Asp Net ArchitectureAsp Net Architecture
Asp Net Architecture
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
Spine.js
Spine.jsSpine.js
Spine.js
 
Laravel
LaravelLaravel
Laravel
 
Meteor iron:router
Meteor iron:routerMeteor iron:router
Meteor iron:router
 
Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...
 
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsCustom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs
 
Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)
 
Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravel
 
Web service with Laravel
Web service with LaravelWeb service with Laravel
Web service with Laravel
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
 

Recently uploaded

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

07-02-05

  • 1. W E D N E S D A Y , A P R I L 1 0 , 2 0 1 3 Handling 404 Error in ASP.NET MVC In ASP.NET Web Forms, handling 404 errors are easy - which is basically a web.config setting. In ASP.NET MVC, it is a bit more complicated. Why is it more complicated? In comparison, everything is seemingly easier in MVC than WebForm. It is more complicated mainly because of Routing. In WebForm, most 404 occurs because of non- existent file and each UR: is usually mapped to a particular file (aspx). With MVC, that is not the case. All requests are handled by the Routing table and based on that it will invoke appropriate controller and actions etc. Secondly, our basic default route usually is quite common ({controller}/{action}/{id}) - therefore most URL request will be caught by this route. So, let's dive in on how can we do proper handling of 404 errors with ASP.NET MVC. TURN ON CUSTOM ERROR IN WEB.CONFIG 1. <customErrors mode="On" defaultRedirect="~/Error/Error"> 2. <error statusCode="404" redirect="~/Error/Http404" /> 3. </customErrors> DECLARE DETAIL ROUTES MAPPED IN ROUTE TABLE So instead of just using the default route: 1. routes.MapRoute( 2. name: "Default", 3. url: "{controller}/{action}/{id}", 4. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 5. ); Declare all your intended route explicitly and create a "catch-all" to handle non-matching route - which basically a 404. In MVC, a 404 can happen when you try to access a URL where the there is no controller for. This code in the routing table handles that scenario. 1. routes.MapRoute(
  • 2. 2. name: "Account", 3. url: "Account/{action}/{id}", 4. defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional } 5. ); 6. 7. routes.MapRoute( 8. name: "Home", 9. url: "Home/{action}/{id}", 10. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 11. ); 12. 13. routes.MapRoute( 14. name: "Admin", 15. url: "Admin/{action}/{id}", 16. defaults: new { controller = "Admin", action = "Index", id = UrlParameter.Optional } 17. ); 18. 19. routes.MapRoute( 20. name: "404-PageNotFound", 21. url: "{*url}", 22. defaults: new { controller = "Home", action = "Http404" } 23. ); OVERRIDE HANDLEUNKNOWNACTION IN BASECONTROLLER CLASS Create a Controller base class that every controller in your application inherits from. In that base controller class, override HandleUnknownAction method. Now, another scenario that a 404 may happen is that when the controller exists, but there is no action for it. In this case, the routing table will not be able to trap it easily - but the controller class has a method that handle that. 1. [AllowAnonymous] 2. public class ErrorController : Controller 3. { 4. protected override void HandleUnknownAction(string actionName) 5. { 6. if (this.GetType() != typeof(ErrorController)) 7. { 8. var errorRoute = new RouteData(); 9. errorRoute.Values.Add("controller", "Error"); 10. errorRoute.Values.Add("action", "Http404");
  • 3. 11. errorRoute.Values.Add("url", HttpContext.Request.Url.OriginalString); 12. 13. View("Http404").ExecuteResult(this.ControllerContext); 14. } 15. } 16. 17. public ActionResult Http404() 18. { 19. return View(); 20. } 21. 22. public ActionResult Error() 23. { 24. return View(); 25. } 26. } CREATE CORRESPONDING VIEWS View for generic error: Error.chtml 1. @model System.Web.Mvc.HandleErrorInfo 2. 3. @{ 4. ViewBag.Title = "Error"; 5. } 6. 7. <hgroup class="title"> 8. <h1 class="error">Error.</h1> 9. <br /> 10. <h2 class="error">An error occurred while processing your request.</h2> 11. @if (Request.IsLocal) 12. { 13. <p> 14. @Model.Exception.StackTrace 15. </p> 16. } 17. else 18. { 19. <h3>@Model.Exception.Message</h3> 20. } 21. </hgroup> View for 404 error: Http404.chtml
  • 4. 1. @model System.Web.Mvc.HandleErrorInfo 2. 3. @{ 4. ViewBag.Title = "404 Error: Page Not Found"; 5. } 6. <hgroup class="title"> 7. <h1 class="error">We Couldn't Find Your Page! (404 Error)</h1><br /> 8. <h2 class="error">Unfortunately, the page you've requested cannot be displayed. </h2><br /> 9. <h2>It appears that you've lost your way either through an outdated link <br />or a typo on the page you were trying to reach.</h2> 10. </hgroup>