Change default view folder for custom Http404 error page
-
24-06-2021 - |
Frage
I want to custom error pages in my asp.net mvc3 website.
So, I found this very useful post: Custom error pages on asp.net MVC3 and it works well
However, my Http404.cshtml
file isn't in the Views
default folder. It is in a folder named BaseViews
.
I already have my _Layout.cshtml
and other views or partial views in that folder.
This folder isn't checked by the default ViewEngine
(it only checks the Views
folder and all the views
folder of my Areas
). So, I use a ViewEngineExtension and add it to the System.Web.Mvc.ViewEngines
collection in my Global.asax
's Application_Start()
. All my application works perfectly fine and can access my layout and other BaseViews
stuff.
I cannot tell the same about the Global.asax
's Application_Error()
. This method ignore the previous view engine and only looks into the default view folder.
I tried to add my ViewEngineExtension in the Application_Error()
method like so ViewEngines.Engines.Add(new BaseViewsEngineExtension());
but it doesn't change anything. It's exactly the same line I use in the Application_Start()
.
See my code for the Application_Error()
:
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "Index";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 404:
routeData.Values["action"] = "Http404";
break;
}
}
IController errorController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorController.Execute(rc);
}
My question is: How can I force errorController.Excecute(rc)
view engine to search my Http404.cshtml view in the BaseViews
folder ?
Lösung
As SLaks said, you should return the full path of your view in your ErrorController.
public class ErrorController : Controller
{
public ActionResult Http404()
{
return View("~/BaseViews/Error/Http404.cshtml");
}
}
But it won't work because your error is overriden, so you don't get the result expected. To bypass this problem, you can tell your application that everything is OK in your application_error with this:
Request.StatusCode = 200;
I hope it'll resolve your problem.
Andere Tipps
Change the Http404
action to return the full path to its view.