, , "" , :
. AFAIK, . , , id
, 3 .
routes.MapRoute(
name: "DefaultWithID",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { action = new ActionExistsConstraint(), id = new ParameterExistsConstraint() }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { action = new ActionExistsConstraint() }
);
routes.MapRoute(
name: "Second",
url: "{*catchall}",
defaults: new { controller = "Home", action = "Index" }
);
ActionExistsConstraint
public class ActionExistsConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest)
{
var action = values["action"] as string;
var controller = values["controller"] as string;
var thisAssembly = this.GetType().Assembly;
Type[] types = thisAssembly.GetTypes();
Type type = types.Where(t => t.Name == (controller + "Controller")).SingleOrDefault();
return type != null && type.GetMethod(action) != null;
}
return true;
}
}
ParameterExistsConstraint
public class ParameterExistsConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest)
{
var action = values["action"] as string;
var controller = values["controller"] as string;
var thisAssembly = this.GetType().Assembly;
Type[] types = thisAssembly.GetTypes();
Type type = types.Where(t => t.Name == (controller + "Controller")).SingleOrDefault();
var method = type.GetMethod(action);
if (type != null && method != null)
{
var param = method.GetParameters().Where(p => p.Name == parameterName).FirstOrDefault();
return param != null;
}
return false;
}
return true;
}
}