asp.net mvc图像路径和虚拟目录

我知道这必须是重复的,但我一直在涉及这方面的大量信息,我无法让它工作。

我正在尝试让一个站点在客户端的服务器上运行,并且他们将站点安装在虚拟目录中。 我本地没有这个设置,所以我在这里失明。

我正在尝试建立一个图像的路径。 (这是Facebook OpenGraph元数据)。

我需要图像的路径是一个完全合格的绝对URL。 我尝试过很多东西,但似乎没什么用。 下面的代码输出一个相对url,但这不起作用。

 <meta property="og:image" content="" /> 

输出:

  

我也尝试过:

  <meta property="og:image" content="" /> 

但那产生了:

  

我正在寻找http://example.com/virtualdirectory/static/images/image.jpg

任何帮助都感激不尽。 我真的不想硬编码url。

谢谢,斯科特

编辑

我忽略了提到我的第一次尝试是Url.Content(“〜/ …. jpg)但是输出了一个相对url,而不是一个相对url。

你可以写一个小的扩展方法:

 public static class UrlExtensions { public static string AbsoluteContent(this UrlHelper url, string contentPath) { var requestUrl = url.RequestContext.HttpContext.Request.Url; return string.Format( "{0}{1}", requestUrl.GetLeftPart(UriPartial.Authority), url.Content(contentPath) ); } } 

然后:

 " /> 

将输出例如:

  

这段代码

 public static class Helpers { public static Uri FullyQualifiedUri( this HtmlHelper html , string relativeOrAbsolutePath ) { Uri baseUri = HttpContext.Current.Request.Url ; string path = UrlHelper.GenerateContentUrl( relativeOrAbsolutePath, new HttpContextWrapper( HttpContext.Current ) ) ; Uri instance = null ; bool ok = Uri.TryCreate( baseUri , path , out instance ) ; return instance ; // instance will be null if the uri could not be created } } 

应该适用于你可以抛出的任何URI。

但有一点需要注意:页面相对URI(例如foo/bar/image.png )可能无法解析您认为的方式,特别是如果URI引用目录,那么您将获得默认页面(即http://localhost/foo/bar可能是一个实际的资源,在这种情况下URI是完整的,或者它可能是不完整的,在这种情况下,Asp.Net MVC的路由填充空白。所有请求都是原始URI。如果你想解决这个问题,你需要获取请求的RouteData并查询它以获取详细信息。

以下是基于http://localhost/MyApp的Web应用程序以及从Home控制器的About视图以不同方式调用Html帮助程序方法的解决方法。

  • ~
    • 解析为http://localhost/MyApp/
  • /
    • 解析为`http:// localhost /
  • ~/
    • 解析为http://localhost/MyApp/
  • foo/bar/myImage.png
    • 解析为http://localhost/MyApp/Home/foo/bar/myImage.png
  • /foo/bar/myImage.png
    • 解析为http://localhost/foo/bar/myImage.png
  • ~/foo/bar/myImage.png
    • 解析为http://localhost/MyApp/foo/bar/myImage.png
  • http://sofzh.miximages.com/c%23/f
    • 解析为http://sofzh.miximages.com/c%23/myImage.png
  • http://somesite.com:123/foo/bar/myImage.png
    • 解析为http://somesite.come:123/foo/bar/myImage.png
  • ftp://somesite.com/foo/bar/myImage.png
    • 解析为ftp://somesite.come:123/foo/bar/myImage.png
  • mailto://local-part@domain.com
    • 解析为mailto:local-part@domain.com

您应该使用路由来解析您的url。

就个人而言,我喜欢遵循以下最佳实践指南 :

创建UrlHelper的扩展方法以从Route生成您的URL

您可能需要这些静态图像的扩展方法:

 public static string StaticImage(this UrlHelper helper, string fileName) { return helper.Content("~/static/images/{0}".FormatWith(fileName)); } 

然后你可以这样做:

 " />