[英]ASP.NET MVC route
我只啟用了默認路由:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
哪個將恢復如下路徑:hostname / Home / Index,hostname / Home / Foo,hostname / Home / Bar / 23就好了。
但是我還必須啟用這樣的路由:hostname / {id}應該指向:
控制器:主頁
行動:指數
{id}:索引操作參數“id”
這樣的路線是否可能?
未測試:像這樣創建您的路線
routes.MapRoute(
name: "custom",
url: "{controller}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
在您的默認路線下
如果id
是一個數字,您可以在另一個上面添加一個路由並定義一個正則表達式約束:
routes.MapRoute(
name: "IdOnlyRoute",
url: "{id}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { id = "^[0-9]+$" }
);
由於我的時間很短,我已經為每個動作配置了路線。 幸運的是,他們並不多。 :)
routes.MapRoute(
name: "IndexWithParam",
url: "{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "IndexWithOutParam",
url: "",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Login",
url: "Home/Login",
defaults: new { controller = "Home", action = "Login" }
);
因此,最后一條路線重復進行其他行動。 不確定它是否可以做得更好,但它確實有效。
你試過使用AttributeRouting包嗎?
然后你的代碼看起來像這樣
[GET("/{id}", IsAbsoluteUrl = true)]
public ActionResult Index(string id) { /* ... */ }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.