我正在尝试配置ASP.NET MVC自定义错误页面。
我添加了一个Error
带有Index
和PageNotFound
动作的控制器。我还在web.config文件的<system.web>
部分中添加了以下内容。
<customErrors mode="On" defaultRedirect="~/Error">
<error statusCode="404" redirect="~/Error/PageNotFound"/>
<error statusCode="500" redirect="~/Error" />
</customErrors>
如果我输入URL,例如http://www.example.com/Home/BadPage,我实际上会看到我的错误处理程序。
但是,谁能帮助我理解以下问题以及如何解决这些问题?
HttpNotFound()
作为结果返回。但是,发生这种情况时,不会显示我的自定义错误处理程序页面。相反,它显示了一个通用404页面,该页面似乎来自IIS。我正在使用Visual Studio和MVC的当前版本。
除了设置里面的web.config,你还需要检查异常是否是HttpException 404内的Application_Error。
<customErrors defaultRedirect="~/Common/Error" mode="On">
<error statusCode="404" redirect="~/Common/PageNotFound"/>
</customErrors>
protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
// Process 404 HTTP errors
var httpException = exception as HttpException;
if (httpException != null && httpException.GetHttpCode() == 404)
{
Response.Clear();
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
IController controller = new CommonController();
var routeData = new RouteData();
routeData.Values.Add("controller", "Common");
routeData.Values.Add("action", "PageNotFound");
var requestContext = new RequestContext(
new HttpContextWrapper(Context), routeData);
controller.Execute(requestContext);
}
}
您还想返回PageNotFoundResponse.StatusCode = 404;
内部的操作方法。
public class CommonController : Controller
{
[AllowAnonymous]
public ActionResult PageNotFound()
{
Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true;
return View();
}
[AllowAnonymous]
public ActionResult Error()
{
Response.StatusCode = 503;
Response.TrySkipIisCustomErrors = true;
return View();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句