
服务器
ASP.NET MVC 404 处理和 IIS7
csharppublic class CustomHandleErrorAttribute : HandleErrorAttribute{ public override void OnException(ExceptionContext filterContext) { if (filterContext.Exception is HttpException && ((HttpException)filterContext.Exception).GetHttpCode() == 404) { filterContext.ExceptionHandled = true; filterContext.Result = new ViewResult { ViewName = "NotFound", ViewData = filterContext.Controller.ViewData, TempData = filterContext.Controller.TempData }; } else { base.OnException(filterContext); } }}在上面的代码中,我们首先判断异常类型是否为 "HttpException",并且状态码是否为 404。如果是,我们将异常标记为已处理,并将结果设置为一个名为 "NotFound" 的自定义视图。在全局筛选器中注册我们的自定义错误处理特性:csharppublic class FilterConfig{ public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new CustomHandleErrorAttribute()); // 其他全局筛选器 }}通过以上配置,当用户访问一个不存在的页面时,将会显示我们指定的自定义视图。使用 IIS7 的 XML<system.webServer> <httpErrors errorMode="Custom"> <remove statusCode="404" subStatusCode="-1" /> <error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" /> </httpErrors></system.webServer>上述配置中,我们首先使用 "remove" 元素将默认的 404 错误处理移除,然后使用 "error" 元素指定自定义错误页面的路径。在上面的示例中,我们假设自定义错误页面的路径为 "/Error/NotFound"。你可以根据实际情况修改路径。无论是使用 ASP.NET MVC 自定义错误处理还是使用 IIS7 的
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号