删除操作和查询字符串之间的斜杠(就像 SO 的搜索行为一样)
我刚刚向我的项目添加了一些搜索功能,该功能运行正常。刚刚使用了SO搜索,我意识到有一个小细节我比我自己的搜索更喜欢,并且我很好奇它是如何实现的,因为我也在使用MVC 3 和 Razor 我的网站。
如果我搜索 SO,我最终会得到一个 URL,例如:
http://stackoverflow.com/search?q=foo
但是,搜索我自己的应用程序会导致:
http://example.com/posts/search/?searchTerms=foo
注意 search
/ > 和 ?
。虽然这纯粹是装饰性的,但我如何从 URL 中删除它,使其最终成为:
http://example.com/posts/search?searchTerms=foo
这是我的搜索路线:
routes.MapRoute(
"SearchPosts",
"posts/search/{*searchTerms}",
new { controller = "Posts", action = "Search", searchTerms = "" }
);
我尝试从路线中删除斜杠,但出现错误。我还尝试添加 ?
而不是斜杠,但这也给出了错误。有好心人可以帮我解开这个谜团吗?
I've just added some search functionality to a project of mine which is working correctly. Having just used the SO search, I realised there is one tiny detail which I prefer to my own search and I became curious as to how it is achieved being as I'm also using MVC 3 and Razor for my site.
If I search SO, I'll end up with a URL such as:
http://stackoverflow.com/search?q=foo
However, searching my own application results in:
http://example.com/posts/search/?searchTerms=foo
Notice the /
between search
and ?
. Although this is purely cosmetic, how can I remove that from the URL so it ends up as:
http://example.com/posts/search?searchTerms=foo
This is my search route:
routes.MapRoute(
"SearchPosts",
"posts/search/{*searchTerms}",
new { controller = "Posts", action = "Search", searchTerms = "" }
);
I've tried removing the slash from the route but that gave an error. I also tried adding in a ?
instead of the slash but that also gave an error. Would anyone be kind enough to solve this mystery for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上,当
searchTerms
可以为null或emptyString时,就没有必要将其放入mapRoute
中。当您尝试通过Html.ActionLink
或Html.RouteLink
创建链接,并向其传递searchTerms
参数时,它将创建searchTerms
作为不带任何斜杠的查询字符串:在 Razor 中:
以及在控制器中:
In fact, when the
searchTerms
can be null-or-emptyString, that is not necessary to put it inmapRoute
. And when you try to create a link byHtml.ActionLink
orHtml.RouteLink
, and pass asearchTerms
parameter to it, it will create thesearchTerms
as a query-string without any slashes:and in Razor:
and in controller: