Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make /views/shared/_layout.cshtml in Razor site return 404 page

I want to have this url (/views/shared/_layout.cshtml) generate a 404 response code & show my custom 404 page. It currently generates this 500 error and stack trace:

Exception Details: System.Web.HttpException: Files with leading underscores ("_") cannot be served.

Stack Trace: [HttpException (0x80004005): Files with leading underscores ("_") cannot be served.] System.Web.WebPages.WebPageRoute.GetRouteLevelMatch(String pathValue, IEnumerable1 supportedExtensions, VirtualPathFactoryManager virtualPathFactoryManager) +291 System.Web.WebPages.WebPageRoute.MatchRequest(String pathValue, IEnumerable1 supportedExtensions, VirtualPathFactoryManager virtualPathFactoryManager) +441 System.Web.WebPages.WebPageRoute.DoPostResolveRequestCache(HttpContextBase context) +222 System.Web.WebPages.WebPageHttpModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) +146 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +220 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +120

like image 860
bkaid Avatar asked Nov 05 '22 02:11

bkaid


2 Answers

Make sure you have the following setting in your Views\web.config file:

<appSettings>
  <add key="webpages:Enabled" value="false" />
</appSettings>
like image 148
marcind Avatar answered Nov 09 '22 11:11

marcind


If you look at the code that throws the exception: it happens because the WebPageHttpModule has hooked up a PostResolveRequestCache handler which tries to resolve the route. It then detects an invalid path and barfs.

Maybe if you are able to register your own IHttpModule before WebPageHttpModule, you can act on the request before the default PostResolveRequestCache handler does.

Yet another option might be to hook into the Application_Error event, and then investigate the exception and return a 404 if appropriate.

like image 29
Grimace of Despair Avatar answered Nov 09 '22 11:11

Grimace of Despair