Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a correct absolute URL when running ASP.NET MVC application under Visual Studio Windows Azure Emulator

I need to create an absolute URL to specific files in my ASP.NET MVC 4 application. I am currently doing this by generating a relative path via Url.Content and then using the following extension method to create the absolute path.

public static string Absolute(this UrlHelper url, string relativeUrl)
{
    var request = url.RequestContext.HttpContext.Request;
    return string.Format("{0}://{1}{2}{3}", 
        (request.IsSecureConnection) ? "https" : "http", 
        request.Url.Host, 
        (request.Url.Port == 80) ? "" : ":" + request.Url.Port, 
        VirtualPathUtility.ToAbsolute(relativeUrl));
}

When running under the Azure Emulator, the proper URL that I need to create is http://127.0.0.1/myfile.jpg but when this code executes, the port number comes back as 81 so the URL that is generated is http://127:0.0.1:81/myfile.jpg. However, if I go to http://127:0.0.1:81/myfile.jpg it of course doesn't work as the Azure Emulator is listening on port 80, not 81.

I assume this has to do with the built in Azure Emulator/IIS Express load balancer, but I am not sure what change I need to make to my Url.Absolute method to return an accurate URL.

like image 810
user2719100 Avatar asked Aug 26 '13 18:08

user2719100


People also ask

How do I get the absolute URL in .NET core?

By specifying the protocol and host, the result is now "https://your-website/Home/Privacy" . However, if you omit the host parameter but keep the protocol parameter, the result will still be an absolute URL, because the host parameter will default to the host used for the current HTTP request.

What is Azure in ASP NET MVC?

Windows Azure platform is Microsoft's cloud solution. Compared to other cloud solutions, the biggest advantage is it seamlessly integrates with Microsoft . NET Framework and the development environment, therefore, regular . NET applications can be moved to Azure effortlessly.


2 Answers

You can rely on the Host header that is being sent by the client:

public static string Absolute(this UrlHelper url, string relativeUrl)
{
    var request = url.RequestContext.HttpContext.Request;

    return string.Format("{0}://{1}{2}",
        (request.IsSecureConnection) ? "https" : "http",
        request.Headers["Host"],
        VirtualPathUtility.ToAbsolute(relativeUrl));
}
like image 65
haim770 Avatar answered Oct 26 '22 22:10

haim770


Why not just use @Url.Content("~/myfile.jpg");? This converts a virtual (relative) path to an application absolute path and works finle in IIS,the emulator and when deployed. See UrlHelper.Content Method

like image 45
viperguynaz Avatar answered Oct 26 '22 22:10

viperguynaz