我在Microsoft Visual Studio Express 2013 for Web中创建了一个新项目。 它是一个ASP.NET MVC 5 - .NET Framework 4.5项目。
我想处理(无法找到资源):
我使用下面的代码处理了它。
如果我执行(/ Home / kddiede / ddiij)或(/ djdied / djie / djs)之类的操作,此代码将起作用,这将导致显示我的自定义错误页面。
但是,当我尝试执行类似(/ Home / kddiede / ddiij / dfd / sdfds / dsf / dsfds / fd)或任何长期不存在的URL时,它会告诉我:
代码来自:http://www.codeproject.com/Articles/635324/Another-set-of-ASP-NET-MVC-4-tips
技巧16:自定义错误屏幕
错误页面位于/View/Shared/Error.cshtml
中的Web.config
<system.web>
<customErrors mode="RemoteOnly" />
</system.web>
Global.asax中
protected void Application_EndRequest(Object sender, EventArgs e)
{
ErrorConfig.Handle(Context);
}
ErrorConfig Class
public class ErrorConfig
{
public static void Handle(HttpContext context)
{
switch (context.Response.StatusCode)
{
//Not authorized
case 401:
Show(context, 401);
break;
//Not found
case 404:
Show(context, 404);
break;
}
}
static void Show(HttpContext context, Int32 code)
{
context.Response.Clear();
var w = new HttpContextWrapper(context);
var c = new ErrorController() as IController;
var rd = new RouteData();
rd.Values["controller"] = "Error";
rd.Values["action"] = "Index";
rd.Values["id"] = code.ToString();
c.Execute(new RequestContext(w, rd));
}
}
ErrorController
internal class ErrorController : Controller
{
[HttpGet]
public ViewResult Index(Int32? id)
{
var statusCode = id.HasValue ? id.Value : 500;
var error = new HandleErrorInfo(new Exception("An exception with error " + statusCode + " occurred!"), "Error", "Index");
return View("Error", error);
}
}
上面提到的网站的最后一段代码没有添加到Global.asax中,因为它已经在FilterConfig.cs中
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
任何人都知道如何修复它?
提前致谢。
答案 0 :(得分:13)
解决。要将所有不存在的URL指向错误页面,请执行以下操作:
在RouteConfig.cs文件的末尾添加以下代码:
public static void RegisterRoutes(RouteCollection routes)
{
// Default
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
// Add this code to handle non-existing urls
routes.MapRoute(
name: "404-PageNotFound",
// This will handle any non-existing urls
url: "{*url}",
// "Shared" is the name of your error controller, and "Error" is the action/page
// that handles all your custom errors
defaults: new { controller = "Shared", action = "Error" }
);
}
将以下代码添加到您的Web.config文件中:
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
</system.webServer>
<system.web>
<httpRuntime relaxedUrlToFileSystemMapping="true" />
</system.web>
</configuration>
这应该将所有不存在的网址(例如(/ad/asd/sa/das,d/asd,asd.asd+dpwd'=12=2e-21)指向您的错误页面。
答案 1 :(得分:5)
另一种方法是将其添加到system.web
元素
<system.web>
<!-- ... -->
<!--Handle application exceptions-->
<customErrors mode="On">
<!--Avoid YSOD on 404/403 errors like this because [HandleErrors] does not catch them-->
<error statusCode="404" redirect="Error/Index" />
<error statusCode="403" redirect="Error/Index" />
</customErrors>
</system.web>