我的問題是關於Pure.Kromes答案this post。我嘗試使用他的方法實現我的頁面的自定義錯誤消息,但有一些問題我無法解釋。ASP.NET MVC自定義錯誤頁面與魔法獨角獸
a) 當我通過輸入無效URL(如localhost:3001/NonexistantPage)導致404錯誤時,它默認爲錯誤控制器的ServerError()操作,即使它應該轉到NotFound()。這是我ErrorController:在Global.asax.cs中
public class ErrorController : Controller { public ActionResult NotFound() { Response.TrySkipIisCustomErrors = true; Response.StatusCode = (int)HttpStatusCode.NotFound; var viewModel = new ErrorViewModel() { ServerException = Server.GetLastError(), HTTPStatusCode = Response.StatusCode }; return View(viewModel); } public ActionResult ServerError() { Response.TrySkipIisCustomErrors = true; Response.StatusCode = (int)HttpStatusCode.InternalServerError; var viewModel = new ErrorViewModel() { ServerException = Server.GetLastError(), HTTPStatusCode = Response.StatusCode }; return View(viewModel); } }
我的錯誤路線:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
name: "Error - 404",
url: "NotFound",
defaults: new { controller = "Error", action = "NotFound" }
);
routes.MapRoute(
name: "Error - 500",
url: "ServerError",
defaults: new { controller = "Error", action = "ServerError" }
);
我的web.config設置:
<system.web>
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="/ServerError">
<error statusCode="404" redirect="/NotFound" />
</customErrors>
...
</system.web>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/NotFound" responseMode="ExecuteURL" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="500" path="/ServerError" responseMode="ExecuteURL" />
</httpErrors>
...
的錯誤觀點位於/ Views/Error/as NotFound.cshtml和ServerError.cshtml。
b) 一個有趣的事情是,當發生服務器錯誤時,它實際上會顯示我定義的服務器錯誤視圖,但它也會輸出一條默認錯誤消息,並說錯誤頁面找不到。
你有什麼建議,我怎麼能解決這兩個問題?我非常喜歡Pure.Kromes的方法來實現這些錯誤信息,但是如果有更好的方法來實現這一點,不要猶豫,告訴我。
謝謝!
**編輯:** 我可以通過ErrorController通過訪問/ Error/NotFound或Error/ServerError直接導航到我的視圖。
視圖本身只包含一些文本,沒有標記或任何東西。
正如我所說的,它實際上以某種方式工作,而不是我打算工作的方式。 web.config中的重定向似乎存在問題,但我一直無法弄清楚。
你也可以發佈你的觀點嗎? 也不要忘記刪除這個'GlobalFilters.Filters.Add(new HandleErrorAttribute());' –
你可以直接導航到你的404頁面嗎? –
是的,我可以。這裏的問題似乎源於web.config中的設置,儘管我找不到那裏的錯誤。 – FLClover