我在global.asax中定义了默认路由
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
我需要实现这一点。
/somecontroller/edit/1
- 当id是一个数字时,就放手吧
/somecontroller/edit/xxxx
- 当id为字符串时,将其重定向到/somecontroller/xxxx
仅在调用动作时才编辑。
答案 0 :(得分:2)
可能你不能只通过路线处理它。您需要在Edit
操作中进行检查,并在字符串值的情况下重定向到Index
操作,否则请处理编辑操作。
路由约束
public class IsIntegerConstraint : IRouteConstraint
{
#region IRouteConstraint Members
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
int result;
return int.TryParse(values[parameterName].ToString(), out result);
}
#endregion
}
<强>路由强>
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { id = new IsIntegerConstraint() }
);
答案 1 :(得分:2)
在RegisterRoutes
方法中,url被转换为控制器,动作和其他参数的名称和值
您可以编写自己的地图路线逻辑 - 将继续执行满足的第一行。
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// empty url is mapping to Home/Index
routes.MapRoute(null, "", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
// accepts "Whatever/Edit/number", where Whatever is controller name (ie Home/Edit/123)
routes.MapRoute(null,
// first is controller name, then text "edit" and then parameter named id
"{controller}/edit/{id}",
// we have to set action manually - it isn't set in url - {action} not set
new { action = "edit"},
new { id = @"\d+" } // id can be only from digits
);
// action name is AFTER edit (ie Home/Edit/MyActionMethod)
routes.MapRoute(null, "{controller}/edit/{action}");
// default action is index -> /Home will map to Home/Index
routes.MapRoute(null, "{controller}", new{action="Index"});
// accepts controller/action (Home/Index or Home/Edit)
routes.MapRoute(null, "{controller}/{action}");
// controller_name/action_name/whatever, where whatever is action method's id parameter (could be string)
routes.MapRoute(null, "{controller}/{action}/{id}");