我试图以这种方式处理MVC5站点中的HTTP错误:
的web.config:
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<clear/>
<error statusCode="403" path="/language/Error/Details/403" responseMode="ExecuteURL"/>
<error statusCode="404" path="/language/Error/Details/404" responseMode="ExecuteURL"/>
<error statusCode="500" path="/language/Error/Details/500" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
ErrorController.cs:
// GET: Error/Details
public ActionResult Details()
{
/* Setting the language for the errors since it is not possible to handle multi-language errors in the web.config file where the errors are redirected */
if (!CultureHelper.cultures.Contains(base.culture))
{
RouteData.Values["culture"] = CultureHelper.GetCurrentNeutralCulture();
}
/* Redirecting uncontrolled errors to 404 error */
if (RouteData.Values["statusCode"] == null)
{
return RedirectToRoute(new { culture = base.culture, controller = "Error", action = "Details", statusCode = 404 });
}
/* Preparing the model */
ErrorViewModel error = ErrorFactory.Create(Convert.ToInt32(RouteData.Values["statusCode"]));
/* Preparing the view */
base.SetLanguageFromRoute();
return View(error);
}
RouteConfig.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { culture = CultureHelper.GetCurrentNeutralCulture(), controller = "User", action = "Home", id = UrlParameter.Optional }
);
routes.MapRoute(
name: null,
url: "{culture}/Error/Details/{statusCode}",
defaults: new { culture = CultureHelper.GetCurrentNeutralCulture() }
);
}
我的问题是,当调用Details GET操作时,一旦它到达此行:
if (RouteData.Values["statusCode"] == null)
它总是返回true,因为没有&#34; statusCode&#34;键入RouteData
,因为它使用默认路由而不是错误路由,并且statusCode
在路由中传递,名称为&#34; id&#34; (默认路由键)。
我知道我可以使用默认路由并从ID中捕获状态代码,但是当我从其他控制器执行RedirectToRoute
错误时我有自定义路由,所以我想使用在这里。有没有办法告诉<httpErrors>
我想使用与默认路线不同的路线?
答案 0 :(得分:-1)
有没有办法告诉我要使用与默认路线不同的路线?
是。有两种方法。
最明智的方法是put specific routes before general routes,因此您的路线表中没有无法到达的执行路径。这可确保您的传入URL定向到正确的控制器。
这意味着您需要在默认路由之前放置更具体的自定义路由,以便首先检查它。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Error",
url: "{culture}/Error/Details/{statusCode}",
defaults: new { culture = CultureHelper.GetCurrentNeutralCulture() }
);
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { culture = CultureHelper.GetCurrentNeutralCulture(), controller = "User", action = "Home", id = UrlParameter.Optional }
);
}
另一种方法是在调用RedirectToRouteResult
时指定路由名称。请注意,您没有为您的路线命名(它为空),因此除非您按照上面的名称命名,否则无法执行此操作。
return RedirectToRoute(
routeName: "Error",
routeValues: new { culture = base.culture, controller = "Error", action = "Details", statusCode = 404 });
这会将您重定向到正确的网址,但可能仍然无法正常运行,因为当访问该网址时,它仍会点击您的&#34;默认&#34;路由,因为它匹配此URL并首先注册。