为什么将 URL 字符串硬编码到 MVC 应用程序中是一个坏主意? (或者是吗?)
In a comment on this question, Phil mentions that
Hardcoding URL strings into an MVC app is a bad idea. The helpers are there for a reason
Is this so? If so, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
URL 生成是应用程序的 global.asax 中路由配置的结果。当您使用 ActionLink 之类的帮助程序时,它们会检查路由配置并相应地生成路由。
如果您稍后更改路由配置,或者将应用程序安装到虚拟目录,则整个应用程序中助手生成的 URL 会动态更改,因此您不必手动检查和更改每个硬编码的 URL 字符串,并且您的应用程序不太可能休息。
如果要标记锚点,可以使用 UrlHelper .操作方法。在内部,所有依赖于 URL 生成的帮助程序都使用此方法。
Url generation is the result of route configuration in your application's global.asax. When you use helpers like ActionLink, they inspect route configuration and generate routes accordingly.
If you change your route configuration later, or install application to virtual directory, URLS generated by helpers in whole application get changed dynamically, so you don't have to inspect and change every hardcoded URL string by hand, and your application is less likely to break.
If you want to markup anchors, you can use UrlHelper.Action Method. Internally all of the helpers which depend on URL generation, use this method.
我编写了一个小网站,其中硬编码了 URL。我现在倾向于避免这种做法,因为一旦投入生产就必须更改所有 URL,这会带来麻烦。
这是一个小型网络应用程序,但它仍然让我感到困惑。我会遵循这个建议:)
I had written a small site that had the URLs hardcoded into it. I tend to avoid the practice now due to the headache it causes of having to change all the URLs as soon as you push to production.
This was a small webapp, and it still drove me up a wall. I would follow that advice :)
我宁愿不使用 Url.Action("Logon","Account"),因为它是硬编码的,并且对操作名称的任何更改都很难识别。
更好的是,我们可以编写一个扩展,例如,
然后在视图中使用它,例如
I would rather not use Url.Action("Logon","Account"), as it is hardcoded and any change to action name, its difficult to identify.
Better we can write a Extension like,
and then use it in the view like,