【问题标题】:Get relative URL in MVC 4在 MVC 4 中获取相对 URL
【发布时间】:2016-09-14 15:26:02
【问题描述】:

我有一个相对路径:

~/Content/themes/base/jquery-ui.min.css"

我有一个隐藏的输入:

<input type="hidden" id="siteUrl" value=""/>

在 MVC 中,我想将完全限定的 URL 存储到隐藏字段中。我试过了:

<input type="hidden" id="siteUrl" value="@Url.RequestContext.HttpContext.Request.MapPath("~/Content/themes/base/jquery-ui.min.css")"/>

<input type="hidden" id="siteUrl" value="@HttpContext.Current.Request.MapPath("~/Content/themes/base/jquery-ui.min.css")"/>

但它们都返回物理路径,我需要 URL。我也尝试过使用UriBuilder,但这对我不起作用,因为虽然它可能在我的本地主机上工作,但当我将它发布到我的 IIS 服务器时却不起作用。

我也试过了:

<input type="hidden" id="siteUrl" value="@Url.Content("~/Content/themes/base/jquery-ui.min.css")"/>

但它返回/Content/themes/base/jquery-ui.min.css

在我的 MVC 控制器中我尝试了:

Page.ResolveClientUrl("~/Content/themes/base/jquery-ui.min.css");

这也不能满足我的需要。

背景:

我将该 FQ URL 存储到隐藏字段中,然后在 JS 中访问它,在 JS 中,当我使用相对 url 时,它不知道如何正确使用它,因为使用 MVC 时,每个链接的路径都会发生变化,它只是将相对字符串到最后是这样的: http://localhost/~/Content/themes/base/jquery-ui.css

如果我只是删除~/,那么它可以工作http://localhost/Content/themes/base/jquery-ui.css,但是当我点击转到新链接时,路径不再是好的:http://localhost/newLink/Content/themes/base/jquery-ui.css

我本地主机上的 URL 是 http://localhost/Content/themes/base/jquery-ui.css 在我的服务器上,它的http://server/productName/Content/themes/base/jquery-ui.css 我不想为一些静态名称编码,以防将来基础服务器 url 发生变化。

那么如何获取相对路径的完全限定 URL?

【问题讨论】:

  • @RoryMcCrossan Server.MapPath 只返回物理路径,我需要完全限定的 URL,即 http://domain.com/productName/Content/...
  • 您的应用程序在生产中部署为“webapplication”,而在开发服务器中作为“网站”运行(这些是 IIS 术语)。区别在于虚拟路径 System.Web.HttpRuntime.AppDomainAppVirtualPath,在本例中为“productName”。使用 @Url.Content("~/Content/themes/base/jquery-ui.min.css") 应该是您所需要的,因为它仅在您需要时包含虚拟路径。您认为这是错误的,因为您没有尝试在 IIS Express 和本地 IIS 中进行部署。在本地 IIS 中部署时,这将包含应用程序名称。

标签: javascript jquery asp.net-mvc asp.net-mvc-4


【解决方案1】:

我不确定您在使用 UriBuilder 时遇到了什么问题,但这是最好的方法:

@{
    var uriBuilder = new UriBuilder(Request.Url);
    uriBuilder.Path = Url.Content("~/Content/themes/base/jquery-ui.min.css");
}
<input type="hidden" id="siteUrl" value="@uriBuilder.ToString()"/>

您从Request.Url 开始,因此您不必对主机进行硬编码。这样,它应该可以在您部署它的任何地方工作。然后您更改Path,但您需要使用Url.Content~ 替换为应该首先使用的任何内容。

您可能还想添加自己的 UrlHelper 扩展:

public static class UrlHelperExtensions
{
    public static string AbsoluteContent(this UrlHelper helper, string contentPath)
    {
        return new Uri(helper.RequestContext.HttpContext.Request.Url, helper.Content(contentPath)).ToString();
    }
}

【讨论】:

  • 太棒了!这行得通,非常感谢,我差点变成秃子了。我想我遇到的问题是因为我使用了Request.Url.AbsolutePath
猜你喜欢
  • 2013-10-25
  • 2016-04-27
  • 2016-05-04
  • 2011-09-09
  • 2013-10-14
  • 2011-07-18
  • 2016-02-15
  • 1970-01-01
相关资源
最近更新 更多