[英]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.