Asp.Net Mvc Route - 错误路由

时间:2016-12-07 14:43:54

标签: c# asp.net asp.net-mvc asp.net-mvc-routing

我正在尝试路由我的应用程序中找不到的错误页面,如果有任何路由错误,则显示错误路由。

我的默认路线

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
    "NotFound",
    "{*.}",
    new { controller = "Error", action = "PageNotFound" }
);

2 个答案:

答案 0 :(得分:1)

点(。)会引起冲突。使用字母字符作为参数名称,

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

//Catch-All InValid (NotFound) Routes
routes.MapRoute(
    name: "NotFound",
    url: "{*url}",
    defaults: new { controller = "Error", action = "PageNotFound" }
);      

它还允许您在动作中获取参数

public class ErrorController : Controller {
    public ActionResult PageNotFound(string url) { ... }
}

如果您想对该值执行任何其他操作。即伐木,审计......等

答案 1 :(得分:0)

在web.config文件中添加。

 <system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error" />
  <remove statusCode="500" />
  <error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>
<modules>
  <remove name="FormsAuthentication" />
</modules>