asp.net-mvc 在 ASP.Net MVC 中获取任何文件的完整 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2069922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting full url of any file in ASP.Net MVC
提问by Gautam Jain
I want to generate complete Url (with domain name etc) of any file in MVC. Example: A .jpgfile or an exefile.
我想在 MVC 中生成任何文件的完整 Url(带有域名等)。示例:一个.jpg文件或一个exe文件。
Example: If I give "~/images/abc.jpg" it should return "http://www.mywebsite.com/images/abc.jpg"
示例:如果我给“~/images/abc.jpg”它应该返回“ http://www.mywebsite.com/images/abc.jpg”
I am aware of the Url.Actionoverload that takes the protocol as a parameter. But Url.Actioncan be used only for Actions.
我知道Url.Action将协议作为参数的重载。但Url.Action只能用于操作。
I want something like Url.Contentfunction that takes protocol as a parameter.
我想要类似Url.Content以协议为参数的函数。
Do you know if any method to get complete url of any file?
您知道是否有任何方法可以获取任何文件的完整 url?
I have tried: VirtualPathUtility.ToAbsolute, ResolveClientUrl, ResolveUrlbut all of these don't seem to work.
我试过:VirtualPathUtility.ToAbsolute, ResolveClientUrl,ResolveUrl但所有这些似乎都不起作用。
回答by arni
new Uri(Request.Url, Url.Content("~/images/image1.gif"))
回答by Adeel
You can use the following code to replace "~/" to absoulute URL.
您可以使用以下代码将“~/”替换为绝对 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.
现在调用此方法将返回完整的绝对 url。
ResolveServerUrl(VirtualPathUtility.ToAbsolute("~/images/image1.gif"),false))
The output will be http://www.yourdomainname.com/images/image1.gif
输出将是 http://www.yourdomainname.com/images/image1.gif
回答by user2166505
Try use this.
试试用这个。
Url.Action("~/images/image1.gif", "/", null, Request.Url.Scheme)

