得到任何文件的完整URL在ASP.Net MVC [英] Getting full url of any file in ASP.Net MVC
问题描述
我要生成完整的URL(以域名等)在MVC中的任何文件。例如:.jpg文件或EXE文件
示例:如果我给〜/图片/ abc.jpg的,它应该返回http://www.mywebsite.com/images/abc.jpg
我知道了Url.Action重载接受该协议作为参数。但Url.Action可以只用于操作。
我想是这样Url.Content函数采用协议作为参数。</ P>
你知道,如果任何方法来得到任何文件的完整的URL?
我曾尝试:VirtualPathUtility.ToAbsolute,ResolveClientUrl,RESOLVEURL但所有这些似乎并没有工作。
。感谢。
您可以使用以下code来代替〜/来absoulute URL。
System.Web.VirtualPathUtility.ToAbsolute(〜/)
编辑:
首先,您需要定义一个方法。
公共静态字符串ResolveServerUrl(字符串的serverUrl,布尔forceHttps)
{
如果(serverUrl.IndexOf(://)-1)〜
返回的serverUrl; 字符串NEWURL =的serverUrl;
乌里originalUri = System.Web.HttpContext.Current.Request.Url;
NEWURL =(forceHttpshttps开头:originalUri.Scheme)+
://+ originalUri.Authority + NEWURL;
返回NEWURL;
}
现在调用此方法将返回完整absolure网址。
ResolveServerUrl(VirtualPathUtility.ToAbsolute(〜/图片/ image1.gif),FALSE))
输出为 http://www.yourdomainname.com/images/image1.gif
I want to generate complete Url (with domain name etc) of any file in MVC. Example: A .jpg file or an exe file.
Example: If I give "~/images/abc.jpg" it should return "http://www.mywebsite.com/images/abc.jpg"
I am aware of the Url.Action overload that takes the protocol as a parameter. But Url.Action can be used only for Actions.
I want something like Url.Content function that takes protocol as a parameter.
Do you know if any method to get complete url of any file?
I have tried: VirtualPathUtility.ToAbsolute, ResolveClientUrl, ResolveUrl but all of these don't seem to work.
Thanks.
You can use the following code to replace "~/" to absoulute URL.
System.Web.VirtualPathUtility.ToAbsolute("~/")
Edit:
First you need to define a method.
public static string ResolveServerUrl(string serverUrl, bool forceHttps)
{
if (serverUrl.IndexOf("://") > -1)
return serverUrl;
string newUrl = serverUrl;
Uri originalUri = System.Web.HttpContext.Current.Request.Url;
newUrl = (forceHttps ? "https" : originalUri.Scheme) +
"://" + originalUri.Authority + newUrl;
return newUrl;
}
Now call this method will return the complete absolure url.
ResolveServerUrl(VirtualPathUtility.ToAbsolute("~/images/image1.gif"),false))
The output will be http://www.yourdomainname.com/images/image1.gif
这篇关于得到任何文件的完整URL在ASP.Net MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!