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

инструкция по созданию кроссвордов
инструкция по созданию кроссвордовинструкция по созданию кроссвордов
инструкция по созданию кроссвордовirina1112
 
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
 
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)

инструкция по созданию кроссвордов
инструкция по созданию кроссвордовинструкция по созданию кроссвордов
инструкция по созданию кроссвордов
 
07-02-05
07-02-0507-02-05
07-02-05
 
pengalaman Sertifikat
pengalaman Sertifikatpengalaman Sertifikat
pengalaman Sertifikat
 
07 02-05
07 02-0507 02-05
07 02-05
 
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
 
07 02-05
07 02-0507 02-05
07 02-05
 
Jd aunipark-commercial-projects-presentation
Jd aunipark-commercial-projects-presentationJd aunipark-commercial-projects-presentation
Jd aunipark-commercial-projects-presentation
 
Инструкция по работе с интернет сервисом "Фабрика кроссвордов"
Инструкция по работе с интернет сервисом "Фабрика кроссвордов"Инструкция по работе с интернет сервисом "Фабрика кроссвордов"
Инструкция по работе с интернет сервисом "Фабрика кроссвордов"
 
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

Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

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>