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";
}
<div class="container">
<h1 class="text-pumpkin">Ruh-roh</h1>
<h3 class="text-wet-asphalt">The page you're looking for isn't here.</h3>
</div>
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
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="403"/>
<remove statusCode="404"/>
<remove statusCode="500"/>
<error statusCode="403" responseMode="ExecuteURL" path="/Error/Forbidden" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>
</system.webServer>
I'd still love to know why this is occurring though.
You can try explicitly setting the ContentType in the action:
public ActionResult NotFound() {
// HACK: fix rendering raw HTML when a controller can't be found
Response.ContentType = "text/html";
return View();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With