我的问题是关于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