簡體   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