Lijin Durairaj
Lijin Durairaj

Reputation: 3501

How to handle 404 error in mvc?

I am trying to handle 404 error in MVC, all other error are being handle using angular so in dont have to worry about other exceptions.

I am handling the 404 error in the Global.asax page like this

 protected void Application_Error()
        {
            // if (Context.IsCustomErrorEnabled)
             ShowCustomErrorPage(Server.GetLastError());
        }
        private void ShowCustomErrorPage(Exception exception)
        {
            var httpException = exception as HttpException ?? new HttpException(500, "Internal Server Error", exception);

            Response.Clear();
            var routeData = new RouteData();
            routeData.Values.Add("controller", "ErrorHandling");
            routeData.Values.Add("fromAppErrorEvent", true);

            switch (httpException.GetHttpCode())
            {
                case 404:
                    routeData.Values.Add("action", "HttpError404");
                    break;
            }

            Server.ClearError();

            IController controller = new ErrorHandlingController();
            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }

but when the 404 error occurs the the Execute method

controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

renders the html of the page instead of the page itself, how to make changes so that i will be able to render the page itself not the html of the page.

Upvotes: 1

Views: 1069

Answers (1)

Alsamil Mehboob
Alsamil Mehboob

Reputation: 404

write following code on your web config

<customErrors mode="On" >
   <error statusCode="404" redirect="~/Controller/CustomErrorPage" />
</customErrors>

Upvotes: 1

Related Questions