I use this code in my Global.asax file to catch all 404 errors and redirect them to a custom controller/view.
protected void Application_Error(object sender, EventArgs e) {
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null) {
if (httpException.GetHttpCode() == 404) {
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
Server.ClearError();
IController errorController = new webbage.chat.Controllers.ErrorController();
Response.StatusCode = 404;
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
}
}
I have three controllers for my application at the moment, Users, Rooms and Home
When I type in something like {localhost}/rooms/999 (this would cause it to throw a 404 since 999 is an invalid room Id), it redirects and renders just fine, everything works as expected.
However if I type in an invalid controller name like so {localhost}/test it redirects it to the view like it should, but when it renders it's just the HTML as plain text. Can someone point out why it would do that?
Here's my ErrorController
public class ErrorController : Controller {
public ActionResult Index() {
return View();
}
public ActionResult NotFound() {
return View();
}
public ActionResult Forbidden() {
return View();
}
}
And my view:
@{
ViewBag.Title = "Error";
}
Ruh-roh
The page you're looking for isn't here.
edit
I ended up going with just web.config error handling since it's much simpler I suppose. I removed the Application_Error code from my Global.asax file and just put this snippet in my web.confg file
I'd still love to know why this is occurring though.