I do error handling (403, 404, 500). To do this, made a separate controller and presentation.

public class ErrorController : Controller { // GET: Error public ActionResult General(Exception exception) { return View("Exception", exception); } public ActionResult Http404() { return View(); } public ActionResult Http403() { return View(); } } 

In Global.asax.cs registered the following method:

 protected void Application_Error() { var exception = Server.GetLastError(); log.Error(exception); Response.Clear(); var httpException = exception as HttpException; var routeData = new RouteData(); routeData.Values.Add("controller", "Error"); if (httpException != null) { Response.StatusCode = httpException.GetHttpCode(); switch (Response.StatusCode) { case 403: routeData.Values.Add("action", "Http403"); break; case 404: routeData.Values.Add("action", "Http404"); break; default: routeData.Values.Add("action", "Error"); break; } } else { routeData.Values.Add("action", "General"); routeData.Values.Add("exception", exception); } Server.ClearError(); Response.TrySkipIisCustomErrors = true; IController errorsController = new ErrorController(); errorsController.Execute(new RequestContext( new HttpContextWrapper(Context), routeData)); } 

If I enter a non-existent controller into the Url (example: http://localhost:62693/123 ), my browser displays the HTML code of my "erroneous" view (instead of the view itself).

If the entered path as a whole does not exist, but the controller is specified correctly in it (example: http://localhost:62693/News/123 ), then the view itself is displayed correctly in the browser.

  • What is the question? What is your expectation? - Andrey NOP
  • @Andrey, I would like to understand why the HTML code is output instead of the view, when I enter a non-existent controller into the Url. And how can this be fixed? - Nikita

1 answer 1

To correct the error, you just need to add

Response.ContentType = "text/html";

and then the view will be returned, not just HTML .

Another way to handle errors.

web.config

 <system.webServer> <httpErrors errorMode="Custom" existingResponse="Replace"> <remove statusCode="404" /> <error statusCode="404" responseMode="ExecuteURL" path="/Error/Http404" /> </httpErrors> </system.webServer> 

Controller

 public class ErrorController : Controller { public ActionResult PageNotFound() { Response.StatusCode = 404; return View(); } } 

It helps me.