gsx*_*y73 8 asp.net-mvc asp.net-mvc-routing catch-all http-status-code-404
当尝试在MVC 4中创建捕获所有路由时(我发现了几个示例,基于我的代码),它返回404错误.我在IIS 7.5上运行它.这似乎是一个直接的解决方案,所以我错过了什么?
需要注意的是,如果我将"CatchAll"路线移到"默认"路线上方,它就可以工作.但是当然没有其他控制器到达过.
这是代码:
Route.Config:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"CatchAll",
"{*dynamicRoute}",
new { controller = "CatchAll", action = "ChoosePage" }
);
Run Code Online (Sandbox Code Playgroud)
控制器:
public class CatchAllController : Controller
{
public ActionResult ChoosePage(string dynamicRoute)
{
ViewBag.Path = dynamicRoute;
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
由于创建捕获路线的最终目标是能够处理动态网址,而我无法找到上述原始问题的直接答案,因此我从不同的角度研究了我的研究.在这样做时,我遇到了这篇博文:当没有路由匹配时自定义404
此解决方案允许处理给定URL中的多个部分(即www.mysite.com/this/is/a/dynamic/route)
这是最终的自定义控制器代码:
public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
{
if (requestContext == null)
{
throw new ArgumentNullException("requestContext");
}
if (String.IsNullOrEmpty(controllerName))
{
throw new ArgumentException("MissingControllerName");
}
var controllerType = GetControllerType(requestContext, controllerName);
// This is where a 404 is normally returned
// Replaced with route to catchall controller
if (controllerType == null)
{
// Build the dynamic route variable with all segments
var dynamicRoute = string.Join("/", requestContext.RouteData.Values.Values);
// Route to the Catchall controller
controllerName = "CatchAll";
controllerType = GetControllerType(requestContext, controllerName);
requestContext.RouteData.Values["Controller"] = controllerName;
requestContext.RouteData.Values["action"] = "ChoosePage";
requestContext.RouteData.Values["dynamicRoute"] = dynamicRoute;
}
IController controller = GetControllerInstance(requestContext, controllerType);
return controller;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5566 次 |
最近记录: |