asp.net mvc图像路径和虚拟目录
我知道这必须是重复的,但我一直在涉及这方面的大量信息,我无法让它工作。
我正在尝试让一个站点在客户端的服务器上运行,并且他们将站点安装在虚拟目录中。 我本地没有这个设置,所以我在这里失明。
我正在尝试建立一个图像的路径。 (这是Facebook OpenGraph元数据)。
我需要图像的路径是一个完全合格的绝对URL。 我尝试过很多东西,但似乎没什么用。 下面的代码输出一个相对url,但这不起作用。
<meta property="og:image" content="" />
输出:
我也尝试过:
<meta property="og:image" content="" />
但那产生了:
我正在寻找https://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引用目录,那么您将获得默认页面(即https://localhost/foo/bar
可能是一个实际的资源,在这种情况下URI是完整的,或者它可能是不完整的,在这种情况下,Asp.Net MVC的路由填充空白。所有请求都是原始URI。如果你想解决这个问题,你需要获取请求的RouteData
并查询它以获取详细信息。
以下是基于https://localhost/MyApp
的Web应用程序以及从Home
控制器的About
视图以不同方式调用Html帮助程序方法的解决方法。
/
~/
foo/bar/myImage.png
/foo/bar/myImage.png
~/foo/bar/myImage.png
https://sofzh.miximages.com/c%23/f
https://somesite.com:123/foo/bar/myImage.png
ftp://somesite.com/foo/bar/myImage.png
mailto://local-part@domain.com
使用UrlHelper
上的Content
方法。
https://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.content.aspx
您应该使用路由来解析您的url。
就个人而言,我喜欢遵循以下最佳实践指南 :
创建UrlHelper的扩展方法以从Route生成您的URL
您可能需要这些静态图像的扩展方法:
public static string StaticImage(this UrlHelper helper, string fileName) { return helper.Content("~/static/images/{0}".FormatWith(fileName)); }
然后你可以这样做:
上述就是C#学习教程:asp.net mvc图像路径和虚拟目录分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
" />
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/936600.html