繁体   English   中英

MVC 在不使用 RAMMFAR 的情况下为带有文件扩展名的 url 捕获 404 错误

[英]MVC Catch 404 errors for urls with file extensions without using RAMMFAR

我对 HttpHandlers 和 HttpModules 做了一些研究,但我不清楚按照我的规范实现它的最佳方法。

我的问题是 StaticFile 处理程序处理所有带有扩展名的 url,并将返回默认的 IIS 404 页面,而不是访问我的ErrorsControllerNotFound操作。 我想使用 MVC 来处理所有 404,因为在 .html 页面上使用 .cshtml 页面的好处以及我执行日志记录和所有 404 响应以及页面包含一些动态内容的事实。

我不想启用<modules runAllManagedModulesForAllRequests="true">因为它会导致性能影响并且因为它似乎是错误的方法。

创建一个 HttpModule 并让它检查请求的文件是否存在,如果没有找到,将请求发送到托管管道并最终发送到我的ErrorsController来处理请求是否ErrorsController

我的解决方案处理来自未经身份验证的用户的所有 404,这包括所有带有文件扩展名的 url。 这个解决方案的ErrorControllerexistingResponse='Auto'确定 404 是否已经由ErrorController处理,如果是,它将跳过这一步,但如果没有,请使用提供的自定义错误页面。

您必须使用Response.TrySkipIisCustomErrors = true;跳过 IIS 自定义错误Response.TrySkipIisCustomErrors = true; .

您可能需要使用Response.StatusCode = (int)HttpStatusCode.NotFound;在方法中再次设置状态代码Response.StatusCode = (int)HttpStatusCode.NotFound;

在你的ErrorController

 [HttpGet]
        public ActionResult 404()
        {
            Response.StatusCode = (int)HttpStatusCode.NotFound;
            Response.TrySkipIisCustomErrors = true;
            return View("Index", new ErrorModel
            {
//Fill in properties values you have in your ErrorModel.
         
            });
        }

在您的webconfig

  <httpErrors errorMode="Custom" existingResponse="Auto">
      <remove statusCode="404" />
      <error statusCode="404" path="/Error/404" responseMode="ExecuteURL" />
    </httpErrors>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM