如何为domain.com/?latest添加路由并处理
我正在尝试处理以下网址:(1)domain.com,(2)domain.com/?latest
这就是我认为应该是的...
Global.asax
routes.MapRoute(
"HomeIndex", // Route name
"/?{sortBy}", // URL with parameters
new { controller = "Home", action = "Index", sortBy = UrlParemeter.Optional } // Parameter defaults
);
HomeController.cs
public ActionResult Index(string sortBy) {
if (string.IsNullOrEmpty(sortBy))
// display stuff in a way that's sorted
else
// just display stuff by default
return View( ... );
}
问题:mvc 不喜欢以硬编码的“?”开头的路由,但是!如果根本不映射路由而只是查找 request.querystring["latest"],它显示为空。
实现这一目标的最佳方法是什么?谢谢!
----- 编辑:
我知道我不应该只使用 /?latest 而应该使用 /?sortBy=latest ,但是,它是一个更短的网址!!!1更容易输入:)我看到谷歌有时会使用它,我想像谷歌一样;)
抛开这不是最好的方法这一事实,有没有办法做到 /?latest ?谢谢!
I'm trying to handle the following url's: (1) domain.com, (2) domain.com/?latest
This is what I think should be it...
Global.asax
routes.MapRoute(
"HomeIndex", // Route name
"/?{sortBy}", // URL with parameters
new { controller = "Home", action = "Index", sortBy = UrlParemeter.Optional } // Parameter defaults
);
HomeController.cs
public ActionResult Index(string sortBy) {
if (string.IsNullOrEmpty(sortBy))
// display stuff in a way that's sorted
else
// just display stuff by default
return View( ... );
}
Issue: mvc doesn't like the route starting with hard-coded "?", but!, if don't map a route at all and just look for request.querystring["latest"], it comes up as null.
What's the best way to accomplish this? Thanks!
------- Edit:
I know that I shouldn't use just /?latest and I should instead use /?sortBy=latest , but, it's a shorter url!!!1 and easier to type :) I see that Google uses it sometimes, and I want to be like Google ;)
Setting aside the fact that it's not the best way to do it, is there a way to do /?latest ? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的查询字符串不完整。试试这个:domain.com/?sortBy=latest。您也可以删除额外的路由映射并使用默认路由。
Your query string is incomplete. Try this: domain.com/?sortBy=latest. You can remove the extra route mapping as well and use the default routing.
您实际上并不需要在路线定义中使用 sortBy 。只需确保操作方法有一个同名的参数即可。
是的,在你的路线中
?latest
部分是不行的。它应该始终采用?varname=varvalue
的形式。You don't really need sortBy in your route definition. Just make sure the action method has an argument with the same name.
And yes, in your route the part
?latest
is not okay. It should always be in the form?varname=varvalue
.