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, IEnumerable
1 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
Make sure you have the following setting in your Views\web.config
file:
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
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.
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