简体   繁体   English

ASP.NET MVC - Url.Content() 的用例是什么?

[英]ASP.NET MVC - What is a use case of Url.Content()?

I cannot, for the life of me, think of any need for this function.在我的一生中,我想不出任何需要这个 function。 MSDN says that it "Converts a virtual (relative) path to an application absolute path.". MSDN 说它“将虚拟(相对)路径转换为应用程序绝对路径。”。 My question is, why are you using a relative path in the first place?我的问题是,你为什么首先使用相对路径?

To illustrate, say you have a file at Scripts/awesome.js.举例来说,假设您在 Scripts/awesome.js 中有一个文件。 You could get to this by doing你可以这样做

<script src="@Url.Content("~/Scripts/awesome.js")"></script>

But you could just as easily get to it using the path directly:但是您可以直接使用路径轻松访问它:

<script src="/Scripts/awesome.js"></script>

The same holds true for any images, CSS or any other static file you might need to reference.这同样适用于任何图像,CSS 或您可能需要参考的任何其他 static 文件。 Can anyone show me a case where this function is needed?谁能告诉我一个需要这个 function 的案例吗?

EDIT:编辑:

Thanks for the answer.感谢你的回答。 The reason I was looking at this is that when I try to do a rewrite to a path at a different depth, this is what breaks the most.我看这个的原因是,当我尝试对不同深度的路径进行重写时,这是最坏的。 See ASP.NET MVC UrlHelper.GenerateUrl exception: "Cannot use a leading.. to exit above the top directory"请参阅ASP.NET MVC UrlHelper.GenerateUrl 异常:“无法使用前导..退出顶级目录”

If your application is running as a sub app (running the site within a folder), you may have a path like http://server.com/app/.. .如果您的应用程序作为子应用程序运行(在文件夹中运行站点),您可能有类似http://server.com/app/..的路径。 In this case an absolute path to /Scripts/... will fail.在这种情况下, /Scripts/...的绝对路径将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM