MVC 相对路径

在我的应用程序中,我经常必须使用相对路径。例如,当我引用 JQuery 时,我通常是这样做的:

<script type="text/javascript" src="../Scripts/jquery-1.2.6.js"></script>

现在我正在转换到 MVC,我需要考虑一个页面相对于根目录可能拥有的不同路径。这当然是过去 URL 重写的一个问题,但我通过使用一致的路径设法解决了这个问题。

我知道标准的解决方案是使用绝对路径,比如:

<script type="text/javascript" src="/Scripts/jquery-1.2.6.js"></script>

但是这对我不起作用,因为在开发周期中,我必须将应用程序部署到一个测试机器上,该机器上的应用程序将在一个虚拟目录中运行。当根更改时,根相对路径不起作用。另外,出于维护原因,我不能简单地在部署测试期间更改所有路径——这本身就是一场噩梦。

那么最好的解决办法是什么?

编辑:

由于这个问题仍然在接收视图和答案,所以我认为更新它是明智的,因为在 Razor V2中,支持根相对 URL,所以您可以使用

<img src="~/Content/MyImage.jpg">

没有任何服务器端语法,并且视图引擎会自动用当前站点根目录替换 ~/。

100183 次浏览

In ASP.NET I usually use <img src='<%= VirtualPathUtility.ToAbsolute("~/images/logo.gif") %>' alt="Our Company Logo"/>. I don't see why a similar solution shouldn't work in ASP.NET MVC.

Try this:

<script type="text/javascript" src="<%=Url.Content("~/Scripts/jquery-1.2.6.js")%>"></script>

Or use MvcContrib and do this:

<%=Html.ScriptInclude("~/Content/Script/jquery.1.2.6.js")%>
<script src="<%=ResolveUrl("~/Scripts/jquery-1.2.6.min.js") %>" type="text/javascript"></script>

Is what I used. Change path to match your example.

For what it's worth, I really hate the idea of littering my app with server tags just to resolve paths, so I did a bit more research and opted to use something I'd tried before for rewriting links - a response filter. In this way, I can prefix all absolute paths with a known prefix and replace it at runtime using the Response.Filter object and not have to worry about unnecessary server tags. The code is posted below in case it will help anyone else.

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;


namespace Demo
{
public class PathRewriter : Stream
{
Stream filter;
HttpContext context;
object writeLock = new object();
StringBuilder sb = new StringBuilder();


Regex eofTag = new Regex("</html>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
Regex rootTag = new Regex("/_AppRoot_", RegexOptions.IgnoreCase | RegexOptions.Compiled);


public PathRewriter(Stream filter, HttpContext context)
{
this.filter = filter;
this.context = context;
}


public override void Write(byte[] buffer, int offset, int count)
{
string temp;


lock (writeLock)
{
temp = Encoding.UTF8.GetString(buffer, offset, count);
sb.Append(temp);


if (eofTag.IsMatch(temp))
RewritePaths();
}
}


public void RewritePaths()
{
byte[] buffer;
string temp;
string root;


temp = sb.ToString();
root = context.Request.ApplicationPath;
if (root == "/") root = "";


temp = rootTag.Replace(temp, root);
buffer = Encoding.UTF8.GetBytes(temp);
filter.Write(buffer, 0, buffer.Length);
}


public override bool CanRead
{
get { return true; }
}


public override bool CanSeek
{
get { return filter.CanSeek; }
}


public override bool CanWrite
{
get { return true; }
}


public override void Flush()
{
return;
}


public override long Length
{
get { return Encoding.UTF8.GetBytes(sb.ToString()).Length; }
}


public override long Position
{
get { return filter.Position; }
set { filter.Position = value; }
}


public override int Read(byte[] buffer, int offset, int count)
{
return filter.Read(buffer, offset, count);
}


public override long Seek(long offset, SeekOrigin origin)
{
return filter.Seek(offset, origin);
}


public override void SetLength(long value)
{
throw new NotImplementedException();
}
}


public class PathFilterModule : IHttpModule
{
public void Dispose()
{
return;
}


public void Init(HttpApplication context)
{
context.ReleaseRequestState += new EventHandler(context_ReleaseRequestState);
}


void context_ReleaseRequestState(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app.Response.ContentType == "text/html")
app.Response.Filter = new PathRewriter(app.Response.Filter, app.Context);
}
}
}

Like Chris, I really can't stand having to put bloated server-side tags inside my clean markup just purely to tell the stupid thing to look from the root upwards. That should be a very simple, reasonable thing to ask for. But I also hate the idea of having to go to the effort of writing any custom C# classes to do such a simple thing, why should I have to? What a waste of time.

For me, I simply compromised on "perfection" and hardcoded the virtual directory's root path name inside my path references. So like this:

<script type="text/javascript" src="/MyProject/Scripts/jquery-1.2.6.js"></script>

No server-side processing or C# code required to resolve the URL, which is best for performance although I know it would be negligible regardless. And no bloated ugly server-side chaos in my nice clean markup.

I'll just have to live with knowing that this is hardcoded and will need to be removed when the thing migrates to a proper domain instead of http://MyDevServer/MyProject/

Cheers

The Razor view engine for MVC 3 makes it even easier and cleaner to use virtual-root relative paths that are properly resolved at run-time. Just drop the Url.Content() method into the href attribute value and it will resolve properly.

<a href="@Url.Content("~/Home")">Application home page</a>

I use a simple helper method. You can easily use it in the Views and Controllers.

Markup:

<a href=@Helper.Root()/about">About Us</a>

Helper method:

public static string Root()
{
if (HttpContext.Current.Request.Url.Host == "localhost")
{
return "";
}
else
{
return "/productionroot";
}
}

While an old post, new readers should know that Razor 2 and later (default in MVC4+) completely resolves this problem.

Old MVC3 with Razor 1:

<a href="@Url.Content("~/Home")">Application home page</a>

New MVC4 with Razor 2 and later:

<a href="~/Home">Application home page</a>

No awkward Razor function-like syntax. No non-standard markup tags.

Prefixing a path in any HTML attributes with a tilde ('~') tells Razor 2 to "just make it work" by substituting the correct path. It's great.

Breaking change - MVC 5

Watch out for a breaking change change in MVC 5 (from the MVC 5 release notes)

Url Rewrite and Tilde(~)

After upgrading to ASP.NET Razor 3 or ASP.NET MVC 5, the tilde(~) notation may no longer work correctly if you are using URL rewrites. The URL rewrite affects the tilde(~) notation in HTML elements such as <A/>, <SCRIPT/>, <LINK/>, and as a result the tilde no longer maps to the root directory.

For example, if you rewrite requests for asp.net/content to asp.net, the href attribute in <A href="~/content/"/> resolves to /content/content/ instead of /. To suppress this change, you can set the IIS_WasUrlRewritten context to false in each Web Page or in Application_BeginRequest in Global.asax.

They don't actually explain how to do it, but then I found this answer:

If you are running in IIS 7 Integrated Pipeline mode try putting the following in your Global.asax:

 protected void Application_BeginRequest(object sender, EventArgs e)
{
Request.ServerVariables.Remove("IIS_WasUrlRewritten");
}

Note: You may want to check Request.ServerVariables actually contains IIS_WasUrlRewritten first to be sure this is what your problem is.


PS. I thought I had a situation where this was happening to me and I was getting src="~/content/..." URLS generated into my HTML - but it turned out something just wasn't refreshing when my code was being compiled. Editing and resaving the Layout and page cshtml files somehow triggered something to work.