asp.net-mvc 为什么要使用@Url.Content("~/blah-blah-blah")?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10468987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:55:33  来源:igfitidea点击:

Why should I use @Url.Content("~/blah-blah-blah")?

asp.net-mvc

提问by Saeed Neamati

I can't understand the benefit(s) that I can get from Url.Content()method in ASP.NET MVC. For example, you see src='@Url.Content("~/Contents/Scripts/jQuery.js")'. Why should I use it? What reasons might exist for using it? What benefits, advantages, etc. over using plain old simple references like src='/scripts/jquery.js?

我无法理解我可以从Url.Content()ASP.NET MVC 中的方法中获得的好处。例如,您看到src='@Url.Content("~/Contents/Scripts/jQuery.js")'. 我为什么要使用它?使用它可能存在哪些原因?与使用简单的旧简单引用相比有什么好处、优势等src='/scripts/jquery.js

Update:Based on the answers, I'd like to know if there is any other reason for using it, other than handling virtual folders? Because I haven't seen using virtual applications that much (which of course doesn't mean that it hasn't been used that much).

更新:根据答案,我想知道除了处理虚拟文件夹之外,是否还有其他原因需要使用它?因为我还没有看到那么多使用虚拟应用程序(这当然并不意味着它没有被使用那么多)。

采纳答案by Adam Tuliper - MSFT

Mapping virtual paths is it's only purpose. If you do not ever need to map them and are sure your app or it folders will not sit under other apps then it won't serve you any purpose.

映射虚拟路径是它的唯一目的。如果您不需要映射它们并且确定您的应用程序或它的文件夹不会位于其他应用程序下,那么它不会为您服务。

From the docs note if you don't use ~ you get no change in the result anyways: "Remarks If the specified content path does not start with the tilde (~) character, this method returns contentPath unchanged. "

从文档注释中,如果您不使用 ~ 无论如何,结果不会发生任何变化:“备注如果指定的内容路径不以波浪号 (~) 字符开头,则此方法返回 contentPath 不变。“

回答by Lotfi

Usually, your web application is published as: www.yoursite.com/. The ~ character matches the root of the site /.

通常,您的 Web 应用程序发布为:www.yoursite.com/。~ 字符匹配站点 / 的根。

However, if you publish your site withing a virtual directory www.yoursite.com/mywebapp/, the the ~ character would match "/mywebapp/". Hard-coding Urls with "/" character would cause wrong page references.

但是,如果您使用虚拟目录 www.yoursite.com/mywebapp/ 发布站点,则 ~ 字符将匹配“/mywebapp/”。带有“/”字符的硬编码 URL 会导致错误的页面引用。

回答by Fox32

It is usefull if your applications root path is not the root path of your server. Url.Content("~/") returns the root folder of your application.

如果您的应用程序根路径不是服务器的根路径,这将很有用。Url.Content("~/") 返回应用程序的根文件夹。