Gautam Jain
Gautam Jain

Reputation: 6849

Getting full url of any file in ASP.Net MVC

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.

Upvotes: 30

Views: 32063

Answers (3)

arni
arni

Reputation: 2407

new Uri(Request.Url, Url.Content("~/images/image1.gif"))

Upvotes: 59

user2166505
user2166505

Reputation: 11

Try use this.

Url.Action("~/images/image1.gif", "/", null, Request.Url.Scheme)

Upvotes: -5

Adeel
Adeel

Reputation: 19238

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

Upvotes: 51

Related Questions