如果CategoryName是可選的,並且LocationName是必填字段,則可以使用Satpal建議。如果這兩個字段是可選的,那麼它不起作用。因爲路由不能確定提供哪個屬性。在這種情況下,你有兩個選擇。一種選擇是定義的參數加上IRouteConstraints不同組合3條不同的路線,
routes.MapRoute(name: "CategoryDetail",
url: "/{controller}/{CategoryDetail}/{LocationName}",
defaults: new { controller = "User", action = "Login" },
constraints: {[email protected]"^\d+$"}
);
routes.MapRoute(name: "CategoryDetail",
url: "/{controller}/{CategoryDetail}/{CategoryName}",
defaults: new { controller = "User", action = "Login" },
constraints: {CategoryName= new GuidConstraint() }
);
routes.MapRoute(name: "CategoryDetail",
url: "/{controller}/{CategoryDetail}/{LocationName}/{CategoryName}",
defaults: new { controller = "User", action = "Login", CategoryName = UrlParameter.Optional }
);
爲GuidConstraint請訪問:here。 或者如果您不喜歡幾條路線,則使用提供的方法here