Donate

ASP.NET MVC 404 Content Page Showing Or Appearing Twice

Good evening gents,

In handling 404 pages (pages that don't exist in the website),I encountered a problem wherein the asp.content tag/control would show twice in the page. Here's the server content code:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">   
   <h2>Page Not Found!</h2>   
   <br />   
   Error in URL Navigation. The page you were looking for was not found.   
  </asp:Content>  
And here's the content being displayed twice.
ASP.NET MVC 404 Content Page Showing Or Appearing Twice
The code I'm using was from a documentation/series on how to handle 404 pages. The tutorial has a controller factory that checks invalid routes and calls the base controller if a route is invalid. Below is the code:
//inherit Controller Class  
   public class BaseController : Controller   
   {  
     private string context;  
     public string MyContextUrl   
     {  
       get  
       {  
         return context;  
       }  
       set  
       {  
         if (value == null)  
         {  
           throw new NullReferenceException();  
         }  
         context = value;  
       }  
     }  
     protected override void HandleUnknownAction(string actionName)  
     {  
       RouteToPage404(HttpContext);  
     }  
     public ActionResult RouteToPage404(HttpContextBase context)  
     {       
         //errorController instance  
         IController errorController = new ErrorController();  
         RouteData rd = new RouteData();  
         rd.Values.Add("controller", "Error");  
         rd.Values.Add("action", "Http404");  
         //execute controller  
         errorController.Execute(new RequestContext(context, rd));  
         return new EmptyResult();  
     }      
   }  
In-order for content to be displayed once, add checking if the controller context is not null.
if (this.ControllerContext != null)  
       {  
         IController errorController = new ErrorController();  
         RouteData rd = new RouteData();  
         rd.Values.Add("controller", "Error");  
         rd.Values.Add("action", "Http404");  
         //execute controller  
         errorController.Execute(new RequestContext(context, rd)); 
         errorController.Execute(new RequestContext(context, rd));  
       } 
 
         return new EmptyResult();   
The 404 controller shown only once.
ASP.NET MVC 404 Content Page Showing Or Appearing Twice
The controller context is not null since ErrorController inherits base controller. The controller factory in turn does not inherit BaseController.

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Pass GUID As Parameter To Action Using ASP.NET MVC ContribGrid